@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/abracadabra-provider.cjs +218 -0
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/abracadabra-provider.esm.js +209 -1
- package/dist/abracadabra-provider.esm.js.map +1 -1
- package/dist/index.d.ts +155 -1
- package/package.json +2 -2
- package/src/NodeIdentity.ts +140 -0
- package/src/ServerRegistry.ts +220 -0
- package/src/index.ts +15 -0
|
@@ -14796,6 +14796,77 @@ async function loginOrRegisterWithKey(client, keypair, opts = {}) {
|
|
|
14796
14796
|
return await client.loginWithKey(keypair.publicKeyB64, sign);
|
|
14797
14797
|
}
|
|
14798
14798
|
}
|
|
14799
|
+
/**
|
|
14800
|
+
* Like {@link loginOrRegisterWithKey}, but probes the server's access policy
|
|
14801
|
+
* first so an un-registered key produces an *actionable* result instead of a raw
|
|
14802
|
+
* register error. This is what lets a running agent say "this server is
|
|
14803
|
+
* invite-only — give me a token, or have an admin authorize my public key"
|
|
14804
|
+
* rather than failing opaquely.
|
|
14805
|
+
*
|
|
14806
|
+
* Flow:
|
|
14807
|
+
* 1. `serverInfo()` (unauthenticated) for the access policy + server name.
|
|
14808
|
+
* 2. Try `loginWithKey`. Success → fetch `getMe()` for the role → `connected`.
|
|
14809
|
+
* 3. On a "not registered" error, branch on the policy:
|
|
14810
|
+
* - an `inviteCode` was supplied → register with it (works for invite-only
|
|
14811
|
+
* and open servers) → re-login → `connected`.
|
|
14812
|
+
* - no code + `invite_only` → `needs_invite`.
|
|
14813
|
+
* - no code + `registration_allowed === false` → `registration_closed`.
|
|
14814
|
+
* - otherwise (open registration) → register without a code → `connected`.
|
|
14815
|
+
* 4. Any other login error propagates.
|
|
14816
|
+
*/
|
|
14817
|
+
async function loginOrRegisterWithPolicy(client, keypair, opts = {}) {
|
|
14818
|
+
const sign = makeChallengeSigner(keypair);
|
|
14819
|
+
const publicKey = keypair.publicKeyB64;
|
|
14820
|
+
let info = {};
|
|
14821
|
+
try {
|
|
14822
|
+
info = await client.serverInfo();
|
|
14823
|
+
} catch {}
|
|
14824
|
+
const serverName = info.name;
|
|
14825
|
+
const connected = async (token) => {
|
|
14826
|
+
let role;
|
|
14827
|
+
try {
|
|
14828
|
+
role = (await client.getMe()).role;
|
|
14829
|
+
} catch {}
|
|
14830
|
+
return {
|
|
14831
|
+
status: "connected",
|
|
14832
|
+
token,
|
|
14833
|
+
publicKey,
|
|
14834
|
+
serverName,
|
|
14835
|
+
role,
|
|
14836
|
+
needsPromotion: role === "observer"
|
|
14837
|
+
};
|
|
14838
|
+
};
|
|
14839
|
+
try {
|
|
14840
|
+
return await connected(await client.loginWithKey(publicKey, sign));
|
|
14841
|
+
} catch (err) {
|
|
14842
|
+
const e = err;
|
|
14843
|
+
const status = e?.status ?? e?.response?.status;
|
|
14844
|
+
const msg = String(e?.message ?? "").toLowerCase();
|
|
14845
|
+
if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
|
|
14846
|
+
if (!opts.inviteCode) {
|
|
14847
|
+
if (info.invite_only === true) return {
|
|
14848
|
+
status: "needs_invite",
|
|
14849
|
+
publicKey,
|
|
14850
|
+
serverName
|
|
14851
|
+
};
|
|
14852
|
+
if (info.registration_allowed === false) return {
|
|
14853
|
+
status: "registration_closed",
|
|
14854
|
+
publicKey,
|
|
14855
|
+
serverName
|
|
14856
|
+
};
|
|
14857
|
+
}
|
|
14858
|
+
opts.onRegister?.();
|
|
14859
|
+
const username = opts.username ?? (opts.displayName ? opts.displayName.replace(/\s+/g, "-").toLowerCase() : void 0);
|
|
14860
|
+
await client.registerWithKey({
|
|
14861
|
+
publicKey,
|
|
14862
|
+
username,
|
|
14863
|
+
displayName: opts.displayName,
|
|
14864
|
+
deviceName: opts.deviceName,
|
|
14865
|
+
inviteCode: opts.inviteCode
|
|
14866
|
+
});
|
|
14867
|
+
return await connected(await client.loginWithKey(publicKey, sign));
|
|
14868
|
+
}
|
|
14869
|
+
}
|
|
14799
14870
|
|
|
14800
14871
|
//#endregion
|
|
14801
14872
|
//#region packages/provider/src/DocUtils.ts
|
|
@@ -15029,6 +15100,143 @@ function pickEntrySpace(roots) {
|
|
|
15029
15100
|
};
|
|
15030
15101
|
}
|
|
15031
15102
|
|
|
15103
|
+
//#endregion
|
|
15104
|
+
//#region packages/provider/src/ServerRegistry.ts
|
|
15105
|
+
/** Resolve the registry path: `ABRA_SERVERS_FILE` env, else `~/.abracadabra/servers.json`. */
|
|
15106
|
+
async function serverRegistryPath(override) {
|
|
15107
|
+
const { homedir } = await import("node:os");
|
|
15108
|
+
const { join } = await import("node:path");
|
|
15109
|
+
return override ?? process.env.ABRA_SERVERS_FILE ?? join(homedir(), ".abracadabra", "servers.json");
|
|
15110
|
+
}
|
|
15111
|
+
/** Default per-server key-file path: `~/.abracadabra/keys/<alias>.key`. */
|
|
15112
|
+
async function defaultKeyFileFor(alias) {
|
|
15113
|
+
const { homedir } = await import("node:os");
|
|
15114
|
+
const { join } = await import("node:path");
|
|
15115
|
+
const safe = alias.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
15116
|
+
return join(homedir(), ".abracadabra", "keys", `${safe}.key`);
|
|
15117
|
+
}
|
|
15118
|
+
/**
|
|
15119
|
+
* Load the registry from disk. A missing file yields an empty registry (never
|
|
15120
|
+
* throws on absence). A malformed file throws so the caller can surface it.
|
|
15121
|
+
*/
|
|
15122
|
+
async function loadServerRegistry(path) {
|
|
15123
|
+
const { existsSync } = await import("node:fs");
|
|
15124
|
+
const { readFile } = await import("node:fs/promises");
|
|
15125
|
+
const file = await serverRegistryPath(path);
|
|
15126
|
+
if (!existsSync(file)) return { servers: {} };
|
|
15127
|
+
const raw = await readFile(file, "utf8");
|
|
15128
|
+
if (!raw.trim()) return { servers: {} };
|
|
15129
|
+
let parsed;
|
|
15130
|
+
try {
|
|
15131
|
+
parsed = JSON.parse(raw);
|
|
15132
|
+
} catch (err) {
|
|
15133
|
+
throw new Error(`Malformed server registry at ${file}: ${err.message}`);
|
|
15134
|
+
}
|
|
15135
|
+
const reg = parsed;
|
|
15136
|
+
return {
|
|
15137
|
+
defaultAlias: reg.defaultAlias,
|
|
15138
|
+
servers: reg.servers ?? {}
|
|
15139
|
+
};
|
|
15140
|
+
}
|
|
15141
|
+
/** Persist the registry, creating `~/.abracadabra/` with `0o700` if needed. */
|
|
15142
|
+
async function saveServerRegistry(reg, path) {
|
|
15143
|
+
const { existsSync } = await import("node:fs");
|
|
15144
|
+
const { writeFile, mkdir } = await import("node:fs/promises");
|
|
15145
|
+
const { dirname } = await import("node:path");
|
|
15146
|
+
const file = await serverRegistryPath(path);
|
|
15147
|
+
const dir = dirname(file);
|
|
15148
|
+
if (!existsSync(dir)) await mkdir(dir, {
|
|
15149
|
+
recursive: true,
|
|
15150
|
+
mode: 448
|
|
15151
|
+
});
|
|
15152
|
+
await writeFile(file, `${JSON.stringify(reg, null, 2)}\n`, { mode: 384 });
|
|
15153
|
+
}
|
|
15154
|
+
/**
|
|
15155
|
+
* Resolve `aliasOrUrl` against the registry.
|
|
15156
|
+
*
|
|
15157
|
+
* - A known alias → its stored profile.
|
|
15158
|
+
* - A bare URL (starts with `http://` / `https://`) → an ephemeral profile with
|
|
15159
|
+
* a derived alias (the URL host) and a default per-host key file. This is NOT
|
|
15160
|
+
* persisted; the caller decides whether to `addServer` it.
|
|
15161
|
+
* - Anything else → `null` (unknown alias).
|
|
15162
|
+
*/
|
|
15163
|
+
async function resolveServer(reg, aliasOrUrl) {
|
|
15164
|
+
const direct = reg.servers[aliasOrUrl];
|
|
15165
|
+
if (direct) return direct;
|
|
15166
|
+
if (/^https?:\/\//i.test(aliasOrUrl)) {
|
|
15167
|
+
let alias = aliasOrUrl;
|
|
15168
|
+
try {
|
|
15169
|
+
alias = new URL(aliasOrUrl).host || aliasOrUrl;
|
|
15170
|
+
} catch {}
|
|
15171
|
+
return {
|
|
15172
|
+
alias,
|
|
15173
|
+
url: aliasOrUrl.replace(/\/+$/, ""),
|
|
15174
|
+
keyFile: await defaultKeyFileFor(alias)
|
|
15175
|
+
};
|
|
15176
|
+
}
|
|
15177
|
+
return null;
|
|
15178
|
+
}
|
|
15179
|
+
/** Add or replace a profile. The first server added becomes the default. */
|
|
15180
|
+
function addServer(reg, profile) {
|
|
15181
|
+
const servers = {
|
|
15182
|
+
...reg.servers,
|
|
15183
|
+
[profile.alias]: profile
|
|
15184
|
+
};
|
|
15185
|
+
return {
|
|
15186
|
+
defaultAlias: reg.defaultAlias && reg.servers[reg.defaultAlias] ? reg.defaultAlias : profile.alias,
|
|
15187
|
+
servers
|
|
15188
|
+
};
|
|
15189
|
+
}
|
|
15190
|
+
/** Remove a profile by alias. Clears `defaultAlias` if it pointed at it. */
|
|
15191
|
+
function removeServer(reg, alias) {
|
|
15192
|
+
if (!reg.servers[alias]) return reg;
|
|
15193
|
+
const servers = { ...reg.servers };
|
|
15194
|
+
delete servers[alias];
|
|
15195
|
+
let defaultAlias = reg.defaultAlias;
|
|
15196
|
+
if (defaultAlias === alias) defaultAlias = Object.keys(servers)[0];
|
|
15197
|
+
return {
|
|
15198
|
+
defaultAlias,
|
|
15199
|
+
servers
|
|
15200
|
+
};
|
|
15201
|
+
}
|
|
15202
|
+
/** Mark `alias` as the default. Throws if the alias is unknown. */
|
|
15203
|
+
function setDefault(reg, alias) {
|
|
15204
|
+
if (!reg.servers[alias]) throw new Error(`Unknown server alias: ${alias}`);
|
|
15205
|
+
return {
|
|
15206
|
+
...reg,
|
|
15207
|
+
defaultAlias: alias
|
|
15208
|
+
};
|
|
15209
|
+
}
|
|
15210
|
+
/**
|
|
15211
|
+
* Seed a `default` profile from a legacy single-key setup when the registry is
|
|
15212
|
+
* empty. Existing MCP/CLI users keep `~/.abracadabra/{agent,cli}.key` and an
|
|
15213
|
+
* `ABRA_URL`; without this they'd lose their identity the first time the
|
|
15214
|
+
* registry takes over. Returns the (possibly unchanged) registry; the caller
|
|
15215
|
+
* persists if `migrated` is true.
|
|
15216
|
+
*
|
|
15217
|
+
* @param url the legacy `ABRA_URL` (no migration without it).
|
|
15218
|
+
* @param legacyKeyFile path to the legacy key (e.g. `~/.abracadabra/agent.key`).
|
|
15219
|
+
*/
|
|
15220
|
+
async function migrateLegacyDefault(reg, url, legacyKeyFile) {
|
|
15221
|
+
if (!url || Object.keys(reg.servers).length > 0) return {
|
|
15222
|
+
registry: reg,
|
|
15223
|
+
migrated: false
|
|
15224
|
+
};
|
|
15225
|
+
const { existsSync } = await import("node:fs");
|
|
15226
|
+
if (!existsSync(legacyKeyFile)) return {
|
|
15227
|
+
registry: reg,
|
|
15228
|
+
migrated: false
|
|
15229
|
+
};
|
|
15230
|
+
return {
|
|
15231
|
+
registry: addServer(reg, {
|
|
15232
|
+
alias: "default",
|
|
15233
|
+
url: url.replace(/\/+$/, ""),
|
|
15234
|
+
keyFile: legacyKeyFile
|
|
15235
|
+
}),
|
|
15236
|
+
migrated: true
|
|
15237
|
+
};
|
|
15238
|
+
}
|
|
15239
|
+
|
|
15032
15240
|
//#endregion
|
|
15033
15241
|
//#region packages/provider/src/DocumentCache.ts
|
|
15034
15242
|
const DB_VERSION$3 = 1;
|
|
@@ -21573,5 +21781,5 @@ var DocumentManager = class {
|
|
|
21573
21781
|
};
|
|
21574
21782
|
|
|
21575
21783
|
//#endregion
|
|
21576
|
-
export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, 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, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, resolvePageType, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
|
|
21784
|
+
export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, 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, 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 };
|
|
21577
21785
|
//# sourceMappingURL=abracadabra-provider.esm.js.map
|