@abraca/dabra 2.101.0 → 2.103.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 +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { sha512 } from "@noble/hashes/sha2.js";
|
|
2
|
+
import * as ed from "@noble/ed25519";
|
|
3
|
+
|
|
4
|
+
//#region packages/provider/src/NodeIdentity.ts
|
|
5
|
+
/**
|
|
6
|
+
* NodeIdentity — Ed25519 identity helpers for Node-side consumers.
|
|
7
|
+
*
|
|
8
|
+
* The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
|
|
9
|
+
* PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
|
|
10
|
+
* `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
|
|
11
|
+
* 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
|
|
12
|
+
* the same challenge → sign → verify flow exposed by
|
|
13
|
+
* {@link AbracadabraClient.loginWithKey}.
|
|
14
|
+
*
|
|
15
|
+
* Every one of those packages previously vendored a near-identical `crypto.ts`
|
|
16
|
+
* (key-file load/create + `signChallenge`) plus a copy-pasted
|
|
17
|
+
* "login → register-on-404 → re-login" block. These helpers are the single
|
|
18
|
+
* shared home for both.
|
|
19
|
+
*
|
|
20
|
+
* The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
|
|
21
|
+
* touches the filesystem, and it does so via dynamic `import("node:…")` so this
|
|
22
|
+
* module stays importable from browser bundles (the fs path simply isn't
|
|
23
|
+
* reachable there).
|
|
24
|
+
*/
|
|
25
|
+
ed.hashes.sha512 = sha512;
|
|
26
|
+
ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
|
|
27
|
+
function toBase64url(bytes) {
|
|
28
|
+
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
29
|
+
}
|
|
30
|
+
function fromBase64url(b64) {
|
|
31
|
+
const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
|
|
32
|
+
const padLen = (4 - padded.length % 4) % 4;
|
|
33
|
+
return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) => c.charCodeAt(0));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Sign a base64url server challenge with a 32-byte Ed25519 seed.
|
|
37
|
+
* Returns a base64url signature suitable for
|
|
38
|
+
* {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
|
|
39
|
+
*/
|
|
40
|
+
function signChallengeWithSeed(challengeB64, seed) {
|
|
41
|
+
return toBase64url(ed.sign(fromBase64url(challengeB64), seed));
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Build the async `signChallenge` callback that
|
|
45
|
+
* {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
|
|
46
|
+
* returned function around to re-authenticate after a JWT expires.
|
|
47
|
+
*/
|
|
48
|
+
function makeChallengeSigner(keypair) {
|
|
49
|
+
return (challenge) => Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Derive a deterministic keypair from a seed string: the same input always
|
|
53
|
+
* yields the same on-server identity. Used by `@abraca/orchestrator` so a named
|
|
54
|
+
* actor maps to one reproducible account across runs.
|
|
55
|
+
*
|
|
56
|
+
* @param salt domain-separation suffix (default `"orchestrator-salt"`, the
|
|
57
|
+
* historical value — change only if you intend a different identity space).
|
|
58
|
+
*/
|
|
59
|
+
function deterministicKeypair(seed, salt = "orchestrator-salt") {
|
|
60
|
+
const privateKey = sha512(new TextEncoder().encode(`${seed}:${salt}`)).slice(0, 32);
|
|
61
|
+
return {
|
|
62
|
+
privateKey,
|
|
63
|
+
publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
|
|
68
|
+
* persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
|
|
69
|
+
* `~/.abracadabra/<defaultFileName>`.
|
|
70
|
+
*
|
|
71
|
+
* Node-only: filesystem modules are loaded via dynamic import, so importing
|
|
72
|
+
* this symbol in a browser bundle is safe — only *calling* it requires Node.
|
|
73
|
+
*/
|
|
74
|
+
async function loadOrCreateKeyFile(keyPath, opts = {}) {
|
|
75
|
+
const { existsSync } = await import("node:fs");
|
|
76
|
+
const { readFile, writeFile, mkdir } = await import("node:fs/promises");
|
|
77
|
+
const { homedir } = await import("node:os");
|
|
78
|
+
const { join, dirname } = await import("node:path");
|
|
79
|
+
const path = keyPath ?? join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
|
|
80
|
+
if (existsSync(path)) {
|
|
81
|
+
const seed = await readFile(path);
|
|
82
|
+
if (seed.length !== 32) throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`);
|
|
83
|
+
const privateKey = new Uint8Array(seed);
|
|
84
|
+
return {
|
|
85
|
+
privateKey,
|
|
86
|
+
publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const privateKey = ed.utils.randomSecretKey();
|
|
90
|
+
const publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));
|
|
91
|
+
const dir = dirname(path);
|
|
92
|
+
if (!existsSync(dir)) await mkdir(dir, {
|
|
93
|
+
recursive: true,
|
|
94
|
+
mode: 448
|
|
95
|
+
});
|
|
96
|
+
await writeFile(path, privateKey, { mode: 384 });
|
|
97
|
+
opts.onCreate?.({
|
|
98
|
+
path,
|
|
99
|
+
publicKeyB64
|
|
100
|
+
});
|
|
101
|
+
return {
|
|
102
|
+
privateKey,
|
|
103
|
+
publicKeyB64
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Authenticate `keypair` against the server, auto-registering on first run.
|
|
108
|
+
*
|
|
109
|
+
* Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
|
|
110
|
+
* — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
|
|
111
|
+
* message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
|
|
112
|
+
* Any other error propagates. Returns the JWT.
|
|
113
|
+
*
|
|
114
|
+
* This is the one shared implementation of the "login → register-on-404 →
|
|
115
|
+
* re-login" dance previously copy-pasted into every Node consumer's connect().
|
|
116
|
+
*/
|
|
117
|
+
async function loginOrRegisterWithKey(client, keypair, opts = {}) {
|
|
118
|
+
const sign = makeChallengeSigner(keypair);
|
|
119
|
+
try {
|
|
120
|
+
return await client.loginWithKey(keypair.publicKeyB64, sign);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
const e = err;
|
|
123
|
+
const status = e?.status ?? e?.response?.status;
|
|
124
|
+
const msg = String(e?.message ?? "").toLowerCase();
|
|
125
|
+
if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
|
|
126
|
+
opts.onRegister?.();
|
|
127
|
+
const username = opts.username ?? (opts.displayName ? opts.displayName.replace(/\s+/g, "-").toLowerCase() : void 0);
|
|
128
|
+
await client.registerWithKey({
|
|
129
|
+
publicKey: keypair.publicKeyB64,
|
|
130
|
+
username,
|
|
131
|
+
displayName: opts.displayName,
|
|
132
|
+
deviceName: opts.deviceName,
|
|
133
|
+
inviteCode: opts.inviteCode
|
|
134
|
+
});
|
|
135
|
+
return await client.loginWithKey(keypair.publicKeyB64, sign);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Like {@link loginOrRegisterWithKey}, but probes the server's access policy
|
|
140
|
+
* first so an un-registered key produces an *actionable* result instead of a raw
|
|
141
|
+
* register error. This is what lets a running agent say "this server is
|
|
142
|
+
* invite-only — give me a token, or have an admin authorize my public key"
|
|
143
|
+
* rather than failing opaquely.
|
|
144
|
+
*
|
|
145
|
+
* Flow:
|
|
146
|
+
* 1. `serverInfo()` (unauthenticated) for the access policy + server name.
|
|
147
|
+
* 2. Try `loginWithKey`. Success → fetch `getMe()` for the role → `connected`.
|
|
148
|
+
* 3. On a "not registered" error, branch on the policy:
|
|
149
|
+
* - an `inviteCode` was supplied → register with it (works for invite-only
|
|
150
|
+
* and open servers) → re-login → `connected`.
|
|
151
|
+
* - no code + `invite_only` → `needs_invite`.
|
|
152
|
+
* - no code + `registration_allowed === false` → `registration_closed`.
|
|
153
|
+
* - otherwise (open registration) → register without a code → `connected`.
|
|
154
|
+
* 4. Any other login error propagates.
|
|
155
|
+
*/
|
|
156
|
+
async function loginOrRegisterWithPolicy(client, keypair, opts = {}) {
|
|
157
|
+
const sign = makeChallengeSigner(keypair);
|
|
158
|
+
const publicKey = keypair.publicKeyB64;
|
|
159
|
+
let info = {};
|
|
160
|
+
try {
|
|
161
|
+
info = await client.serverInfo();
|
|
162
|
+
} catch {}
|
|
163
|
+
const serverName = info.name;
|
|
164
|
+
const connected = async (token) => {
|
|
165
|
+
let role;
|
|
166
|
+
try {
|
|
167
|
+
role = (await client.getMe()).role;
|
|
168
|
+
} catch {}
|
|
169
|
+
return {
|
|
170
|
+
status: "connected",
|
|
171
|
+
token,
|
|
172
|
+
publicKey,
|
|
173
|
+
serverName,
|
|
174
|
+
role,
|
|
175
|
+
needsPromotion: role === "observer"
|
|
176
|
+
};
|
|
177
|
+
};
|
|
178
|
+
try {
|
|
179
|
+
return await connected(await client.loginWithKey(publicKey, sign));
|
|
180
|
+
} catch (err) {
|
|
181
|
+
const e = err;
|
|
182
|
+
const status = e?.status ?? e?.response?.status;
|
|
183
|
+
const msg = String(e?.message ?? "").toLowerCase();
|
|
184
|
+
if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
|
|
185
|
+
if (!opts.inviteCode) {
|
|
186
|
+
if (info.invite_only === true) return {
|
|
187
|
+
status: "needs_invite",
|
|
188
|
+
publicKey,
|
|
189
|
+
serverName
|
|
190
|
+
};
|
|
191
|
+
if (info.registration_allowed === false) return {
|
|
192
|
+
status: "registration_closed",
|
|
193
|
+
publicKey,
|
|
194
|
+
serverName
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
opts.onRegister?.();
|
|
198
|
+
const username = opts.username ?? (opts.displayName ? opts.displayName.replace(/\s+/g, "-").toLowerCase() : void 0);
|
|
199
|
+
await client.registerWithKey({
|
|
200
|
+
publicKey,
|
|
201
|
+
username,
|
|
202
|
+
displayName: opts.displayName,
|
|
203
|
+
deviceName: opts.deviceName,
|
|
204
|
+
inviteCode: opts.inviteCode
|
|
205
|
+
});
|
|
206
|
+
return await connected(await client.loginWithKey(publicKey, sign));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
//#endregion
|
|
211
|
+
export { deterministicKeypair, loadOrCreateKeyFile, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, signChallengeWithSeed };
|
|
212
|
+
//# sourceMappingURL=NodeIdentity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NodeIdentity.js","names":[],"sources":["../../src/NodeIdentity.ts"],"sourcesContent":["/**\n * NodeIdentity — Ed25519 identity helpers for Node-side consumers.\n *\n * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn\n * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,\n * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw\n * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with\n * the same challenge → sign → verify flow exposed by\n * {@link AbracadabraClient.loginWithKey}.\n *\n * Every one of those packages previously vendored a near-identical `crypto.ts`\n * (key-file load/create + `signChallenge`) plus a copy-pasted\n * \"login → register-on-404 → re-login\" block. These helpers are the single\n * shared home for both.\n *\n * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}\n * touches the filesystem, and it does so via dynamic `import(\"node:…\")` so this\n * module stays importable from browser bundles (the fs path simply isn't\n * reachable there).\n */\n\nimport * as ed from \"@noble/ed25519\";\nimport { sha512 } from \"@noble/hashes/sha2.js\";\n\n// @noble/ed25519 v3: wire sha512 for the sync sign/getPublicKey paths and an\n// async hook for *Async variants. Idempotent with the same assignment in\n// CryptoIdentityKeystore / MnemonicKeyDerivation — whichever module loads first\n// wins, and the value is identical.\ned.hashes.sha512 = sha512;\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));\n\n// ── base64url (browser-safe; mirrors CryptoIdentityKeystore) ─────────────────\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\tconst padded = b64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padLen = (4 - (padded.length % 4)) % 4;\n\treturn Uint8Array.from(atob(padded + \"=\".repeat(padLen)), (c) =>\n\t\tc.charCodeAt(0),\n\t);\n}\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/** A raw Node Ed25519 identity: 32-byte seed + base64url public key. */\nexport interface NodeKeypair {\n\t/** 32-byte Ed25519 private-key seed. */\n\tprivateKey: Uint8Array;\n\t/** base64url-encoded 32-byte Ed25519 public key. */\n\tpublicKeyB64: string;\n}\n\n/** Options for {@link loadOrCreateKeyFile}. */\nexport interface LoadKeyFileOptions {\n\t/**\n\t * File name under `~/.abracadabra/` used when `keyPath` is not given.\n\t * Lets each consumer keep its own identity slot (e.g. `\"cli.key\"`,\n\t * `\"agent.key\"`). Defaults to `\"identity.key\"`.\n\t */\n\tdefaultFileName?: string;\n\t/** Invoked once when a brand-new key is generated (for logging). */\n\tonCreate?: (info: { path: string; publicKeyB64: string }) => void;\n}\n\n/** Minimal client surface needed by {@link loginOrRegisterWithKey}. */\nexport interface KeyAuthClient {\n\tloginWithKey(\n\t\tpublicKey: string,\n\t\tsignChallenge: (challenge: string) => Promise<string>,\n\t): Promise<string>;\n\tregisterWithKey(opts: {\n\t\tpublicKey: string;\n\t\tusername?: string;\n\t\tdisplayName?: string;\n\t\tdeviceName?: string;\n\t\tinviteCode?: string;\n\t}): Promise<unknown>;\n}\n\n/**\n * Wider client surface needed by {@link loginOrRegisterWithPolicy}: it probes\n * `serverInfo()` (unauthenticated) to decide the access policy and reads\n * `getMe()` after connecting to detect a read-only (un-promoted) role.\n */\nexport interface PolicyAuthClient extends KeyAuthClient {\n\tserverInfo(): Promise<{\n\t\tname?: string;\n\t\tregistration_allowed?: boolean;\n\t\tinvite_only?: boolean;\n\t\taccess?: { authenticated?: string };\n\t}>;\n\tgetMe(): Promise<{ role?: string }>;\n}\n\n/**\n * Outcome of {@link loginOrRegisterWithPolicy}. A discriminated union so callers\n * (MCP `connect_server`, CLI `server login`) can render an actionable message.\n *\n * - `connected` — logged in (existing account) or registered (open server / valid\n * invite). `needsPromotion` is set when the account is read-only (`observer`),\n * so the caller can suggest an admin grant a write role to `publicKey`.\n * - `needs_invite` — server is invite-only, the key isn't registered, and no\n * invite code was supplied. Surface `publicKey` so an admin can authorize it by\n * hand if no token is available.\n * - `registration_closed` — open registration is disabled; only an admin can\n * provision the account. Surface `publicKey`.\n */\nexport type ConnectPolicyResult =\n\t| {\n\t\t\tstatus: \"connected\";\n\t\t\ttoken: string;\n\t\t\tpublicKey: string;\n\t\t\tserverName?: string;\n\t\t\trole?: string;\n\t\t\tneedsPromotion: boolean;\n\t }\n\t| { status: \"needs_invite\"; publicKey: string; serverName?: string }\n\t| { status: \"registration_closed\"; publicKey: string; serverName?: string };\n\n/** Options for {@link loginOrRegisterWithKey}. */\nexport interface LoginOrRegisterOptions {\n\t/**\n\t * Account username. Defaults to a slug of `displayName`\n\t * (`/\\s+/g → \"-\"`, lowercased) when omitted.\n\t */\n\tusername?: string;\n\tdisplayName?: string;\n\tdeviceName?: string;\n\tinviteCode?: string;\n\t/** Invoked right before auto-registering on first run (for logging). */\n\tonRegister?: () => void;\n}\n\n// ── Signing ──────────────────────────────────────────────────────────────────\n\n/**\n * Sign a base64url server challenge with a 32-byte Ed25519 seed.\n * Returns a base64url signature suitable for\n * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).\n */\nexport function signChallengeWithSeed(\n\tchallengeB64: string,\n\tseed: Uint8Array,\n): string {\n\treturn toBase64url(ed.sign(fromBase64url(challengeB64), seed));\n}\n\n/**\n * Build the async `signChallenge` callback that\n * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the\n * returned function around to re-authenticate after a JWT expires.\n */\nexport function makeChallengeSigner(\n\tkeypair: NodeKeypair,\n): (challenge: string) => Promise<string> {\n\treturn (challenge: string) =>\n\t\tPromise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));\n}\n\n/**\n * Derive a deterministic keypair from a seed string: the same input always\n * yields the same on-server identity. Used by `@abraca/orchestrator` so a named\n * actor maps to one reproducible account across runs.\n *\n * @param salt domain-separation suffix (default `\"orchestrator-salt\"`, the\n * historical value — change only if you intend a different identity space).\n */\nexport function deterministicKeypair(\n\tseed: string,\n\tsalt = \"orchestrator-salt\",\n): NodeKeypair {\n\tconst privateKey = sha512(\n\t\tnew TextEncoder().encode(`${seed}:${salt}`),\n\t).slice(0, 32);\n\treturn { privateKey, publicKeyB64: toBase64url(ed.getPublicKey(privateKey)) };\n}\n\n// ── Key file (Node only) ─────────────────────────────────────────────────────\n\n/**\n * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and\n * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is\n * `~/.abracadabra/<defaultFileName>`.\n *\n * Node-only: filesystem modules are loaded via dynamic import, so importing\n * this symbol in a browser bundle is safe — only *calling* it requires Node.\n */\nexport async function loadOrCreateKeyFile(\n\tkeyPath?: string,\n\topts: LoadKeyFileOptions = {},\n): Promise<NodeKeypair> {\n\tconst { existsSync } = await import(\"node:fs\");\n\tconst { readFile, writeFile, mkdir } = await import(\"node:fs/promises\");\n\tconst { homedir } = await import(\"node:os\");\n\tconst { join, dirname } = await import(\"node:path\");\n\n\tconst path =\n\t\tkeyPath ??\n\t\tjoin(homedir(), \".abracadabra\", opts.defaultFileName ?? \"identity.key\");\n\n\tif (existsSync(path)) {\n\t\tconst seed = await readFile(path);\n\t\tif (seed.length !== 32) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,\n\t\t\t);\n\t\t}\n\t\tconst privateKey = new Uint8Array(seed);\n\t\treturn {\n\t\t\tprivateKey,\n\t\t\tpublicKeyB64: toBase64url(ed.getPublicKey(privateKey)),\n\t\t};\n\t}\n\n\tconst privateKey = ed.utils.randomSecretKey();\n\tconst publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));\n\n\tconst dir = dirname(path);\n\tif (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });\n\tawait writeFile(path, privateKey, { mode: 0o600 });\n\n\topts.onCreate?.({ path, publicKeyB64 });\n\treturn { privateKey, publicKeyB64 };\n}\n\n// ── Login / register ─────────────────────────────────────────────────────────\n\n/**\n * Authenticate `keypair` against the server, auto-registering on first run.\n *\n * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet\n * — signalled by HTTP 404/422, or 401 with a \"not registered / user not found\"\n * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.\n * Any other error propagates. Returns the JWT.\n *\n * This is the one shared implementation of the \"login → register-on-404 →\n * re-login\" dance previously copy-pasted into every Node consumer's connect().\n */\nexport async function loginOrRegisterWithKey(\n\tclient: KeyAuthClient,\n\tkeypair: NodeKeypair,\n\topts: LoginOrRegisterOptions = {},\n): Promise<string> {\n\tconst sign = makeChallengeSigner(keypair);\n\ttry {\n\t\treturn await client.loginWithKey(keypair.publicKeyB64, sign);\n\t} catch (err: unknown) {\n\t\tconst e = err as { status?: number; response?: { status?: number }; message?: string };\n\t\tconst status = e?.status ?? e?.response?.status;\n\t\tconst msg = String(e?.message ?? \"\").toLowerCase();\n\t\tconst notRegistered =\n\t\t\tstatus === 404 ||\n\t\t\tstatus === 422 ||\n\t\t\t(status === 401 && /not registered|user not found|no such user/.test(msg));\n\t\tif (!notRegistered) throw err;\n\n\t\topts.onRegister?.();\n\t\tconst username =\n\t\t\topts.username ??\n\t\t\t(opts.displayName\n\t\t\t\t? opts.displayName.replace(/\\s+/g, \"-\").toLowerCase()\n\t\t\t\t: undefined);\n\t\tawait client.registerWithKey({\n\t\t\tpublicKey: keypair.publicKeyB64,\n\t\t\tusername,\n\t\t\tdisplayName: opts.displayName,\n\t\t\tdeviceName: opts.deviceName,\n\t\t\tinviteCode: opts.inviteCode,\n\t\t});\n\t\treturn await client.loginWithKey(keypair.publicKeyB64, sign);\n\t}\n}\n\n/**\n * Like {@link loginOrRegisterWithKey}, but probes the server's access policy\n * first so an un-registered key produces an *actionable* result instead of a raw\n * register error. This is what lets a running agent say \"this server is\n * invite-only — give me a token, or have an admin authorize my public key\"\n * rather than failing opaquely.\n *\n * Flow:\n * 1. `serverInfo()` (unauthenticated) for the access policy + server name.\n * 2. Try `loginWithKey`. Success → fetch `getMe()` for the role → `connected`.\n * 3. On a \"not registered\" error, branch on the policy:\n * - an `inviteCode` was supplied → register with it (works for invite-only\n * and open servers) → re-login → `connected`.\n * - no code + `invite_only` → `needs_invite`.\n * - no code + `registration_allowed === false` → `registration_closed`.\n * - otherwise (open registration) → register without a code → `connected`.\n * 4. Any other login error propagates.\n */\nexport async function loginOrRegisterWithPolicy(\n\tclient: PolicyAuthClient,\n\tkeypair: NodeKeypair,\n\topts: LoginOrRegisterOptions = {},\n): Promise<ConnectPolicyResult> {\n\tconst sign = makeChallengeSigner(keypair);\n\tconst publicKey = keypair.publicKeyB64;\n\n\t// Best-effort policy probe — never fatal (older servers may omit fields).\n\tlet info: Awaited<ReturnType<PolicyAuthClient[\"serverInfo\"]>> = {};\n\ttry {\n\t\tinfo = await client.serverInfo();\n\t} catch {\n\t\t/* fall through with empty policy → behave like open/unknown */\n\t}\n\tconst serverName = info.name;\n\n\tconst connected = async (token: string): Promise<ConnectPolicyResult> => {\n\t\tlet role: string | undefined;\n\t\ttry {\n\t\t\trole = (await client.getMe()).role;\n\t\t} catch {\n\t\t\t/* role unknown — don't block the connection on it */\n\t\t}\n\t\t// A bare `observer` is the read-only floor: connected, but can't write\n\t\t// until an admin promotes the key. `service`/`admin`/`owner`/`editor` are\n\t\t// write-capable; `viewer` is intentionally read-only by grant, not a\n\t\t// missing-promotion signal, so only flag `observer`.\n\t\tconst needsPromotion = role === \"observer\";\n\t\treturn {\n\t\t\tstatus: \"connected\",\n\t\t\ttoken,\n\t\t\tpublicKey,\n\t\t\tserverName,\n\t\t\trole,\n\t\t\tneedsPromotion,\n\t\t};\n\t};\n\n\ttry {\n\t\treturn await connected(await client.loginWithKey(publicKey, sign));\n\t} catch (err: unknown) {\n\t\tconst e = err as {\n\t\t\tstatus?: number;\n\t\t\tresponse?: { status?: number };\n\t\t\tmessage?: string;\n\t\t};\n\t\tconst status = e?.status ?? e?.response?.status;\n\t\tconst msg = String(e?.message ?? \"\").toLowerCase();\n\t\tconst notRegistered =\n\t\t\tstatus === 404 ||\n\t\t\tstatus === 422 ||\n\t\t\t(status === 401 && /not registered|user not found|no such user/.test(msg));\n\t\tif (!notRegistered) throw err;\n\n\t\t// Not registered — decide based on policy + whether we have a code.\n\t\tif (!opts.inviteCode) {\n\t\t\tif (info.invite_only === true) {\n\t\t\t\treturn { status: \"needs_invite\", publicKey, serverName };\n\t\t\t}\n\t\t\tif (info.registration_allowed === false) {\n\t\t\t\treturn { status: \"registration_closed\", publicKey, serverName };\n\t\t\t}\n\t\t}\n\n\t\topts.onRegister?.();\n\t\tconst username =\n\t\t\topts.username ??\n\t\t\t(opts.displayName\n\t\t\t\t? opts.displayName.replace(/\\s+/g, \"-\").toLowerCase()\n\t\t\t\t: undefined);\n\t\tawait client.registerWithKey({\n\t\t\tpublicKey,\n\t\t\tusername,\n\t\t\tdisplayName: opts.displayName,\n\t\t\tdeviceName: opts.deviceName,\n\t\t\tinviteCode: opts.inviteCode,\n\t\t});\n\t\treturn await connected(await client.loginWithKey(publicKey, sign));\n\t}\n}\n"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
|
4
|
+
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
5
|
+
/**
|
|
6
|
+
* Thin façade over the `messages:inbox_*` stateless protocol.
|
|
7
|
+
*
|
|
8
|
+
* Per-user notifications live as Y.Array entries on the user's inbox doc
|
|
9
|
+
* (`kind = "inbox"`, owned by the user, child of the server root, server-only
|
|
10
|
+
* writer). Real-time observation of new entries is a Y.Array observer the
|
|
11
|
+
* consumer attaches via `AbracadabraProvider` on the inbox doc.
|
|
12
|
+
*
|
|
13
|
+
* This client handles only the request/response layer:
|
|
14
|
+
* - `fetch()` issues `messages:inbox_fetch`, returns the entry list.
|
|
15
|
+
* - `markRead()` issues `messages:inbox_mark_read` (id / ids / source_id /
|
|
16
|
+
* all variants).
|
|
17
|
+
*
|
|
18
|
+
* For incoming notification observation, open an AbracadabraProvider on the
|
|
19
|
+
* inbox doc and observe its `entries` Y.Array directly. The dashboard's
|
|
20
|
+
* `useNotifications` composable does this.
|
|
21
|
+
*/
|
|
22
|
+
var NotificationsClient = class extends EventEmitter {
|
|
23
|
+
constructor(provider, options) {
|
|
24
|
+
super();
|
|
25
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
26
|
+
this.provider = provider;
|
|
27
|
+
this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
28
|
+
this.boundOnStateless = (data) => this.handleStateless(data.payload);
|
|
29
|
+
this.boundOnServerError = (data) => this.handleServerError(data);
|
|
30
|
+
this.provider.on("stateless", this.boundOnStateless);
|
|
31
|
+
this.provider.on("serverError", this.boundOnServerError);
|
|
32
|
+
}
|
|
33
|
+
destroy() {
|
|
34
|
+
this.provider.off("stateless", this.boundOnStateless);
|
|
35
|
+
this.provider.off("serverError", this.boundOnServerError);
|
|
36
|
+
for (const queue of this.pending.values()) for (const p of queue) {
|
|
37
|
+
clearTimeout(p.timer);
|
|
38
|
+
p.reject(/* @__PURE__ */ new Error("NotificationsClient destroyed"));
|
|
39
|
+
}
|
|
40
|
+
this.pending.clear();
|
|
41
|
+
this.removeAllListeners();
|
|
42
|
+
}
|
|
43
|
+
/** Fetch a slice of the calling user's inbox. Resolves with the entries. */
|
|
44
|
+
fetch(input = {}) {
|
|
45
|
+
const promise = this.enqueue("messages:inbox_history");
|
|
46
|
+
this.provider.sendStateless(JSON.stringify({
|
|
47
|
+
type: "messages:inbox_fetch",
|
|
48
|
+
...input.before !== void 0 ? { before: input.before } : {},
|
|
49
|
+
...input.limit !== void 0 ? { limit: input.limit } : {},
|
|
50
|
+
...input.unread_only !== void 0 ? { unread_only: input.unread_only } : {}
|
|
51
|
+
}));
|
|
52
|
+
return promise;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Mark inbox entries read. One of `id`, `ids`, `source_id`, or `all`.
|
|
56
|
+
* Returns when the server has acked.
|
|
57
|
+
*/
|
|
58
|
+
markRead(input) {
|
|
59
|
+
const body = { type: "messages:inbox_mark_read" };
|
|
60
|
+
if (input.all === true) body.all = true;
|
|
61
|
+
else if (input.source_id !== void 0) body.source_id = input.source_id;
|
|
62
|
+
else if (input.ids !== void 0) body.ids = input.ids;
|
|
63
|
+
else if (input.id !== void 0) body.id = input.id;
|
|
64
|
+
else return Promise.reject(/* @__PURE__ */ new Error("markRead: one of id/ids/source_id/all required"));
|
|
65
|
+
const promise = this.enqueue("messages:inbox_mark_read");
|
|
66
|
+
this.provider.sendStateless(JSON.stringify(body));
|
|
67
|
+
return promise;
|
|
68
|
+
}
|
|
69
|
+
enqueue(source) {
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
const entry = {
|
|
72
|
+
resolve,
|
|
73
|
+
reject,
|
|
74
|
+
timer: setTimeout(() => {
|
|
75
|
+
this.removePending(source, entry);
|
|
76
|
+
reject(/* @__PURE__ */ new Error(`NotificationsClient: timeout waiting for ${source}`));
|
|
77
|
+
}, this.responseTimeoutMs)
|
|
78
|
+
};
|
|
79
|
+
const queue = this.pending.get(source) ?? [];
|
|
80
|
+
queue.push(entry);
|
|
81
|
+
this.pending.set(source, queue);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
removePending(source, entry) {
|
|
85
|
+
const queue = this.pending.get(source);
|
|
86
|
+
if (!queue) return;
|
|
87
|
+
const idx = queue.indexOf(entry);
|
|
88
|
+
if (idx >= 0) queue.splice(idx, 1);
|
|
89
|
+
if (queue.length === 0) this.pending.delete(source);
|
|
90
|
+
}
|
|
91
|
+
resolveNext(source, value) {
|
|
92
|
+
const queue = this.pending.get(source);
|
|
93
|
+
if (!queue || queue.length === 0) return false;
|
|
94
|
+
const next = queue.shift();
|
|
95
|
+
if (queue.length === 0) this.pending.delete(source);
|
|
96
|
+
clearTimeout(next.timer);
|
|
97
|
+
next.resolve(value);
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
rejectNext(source, err) {
|
|
101
|
+
const queue = this.pending.get(source);
|
|
102
|
+
if (!queue || queue.length === 0) return false;
|
|
103
|
+
const next = queue.shift();
|
|
104
|
+
if (queue.length === 0) this.pending.delete(source);
|
|
105
|
+
clearTimeout(next.timer);
|
|
106
|
+
next.reject(err);
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
handleStateless(payload) {
|
|
110
|
+
let parsed;
|
|
111
|
+
try {
|
|
112
|
+
parsed = JSON.parse(payload);
|
|
113
|
+
} catch {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const type = parsed?.type;
|
|
117
|
+
if (typeof type !== "string") return;
|
|
118
|
+
if (type === "messages:inbox_history") {
|
|
119
|
+
this.resolveNext("messages:inbox_history", { entries: parsed.entries ?? [] });
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (type === "messages:ok" && parsed.source === "messages:inbox_mark_read") {
|
|
123
|
+
this.resolveNext("messages:inbox_mark_read", void 0);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
handleServerError(data) {
|
|
128
|
+
if (data.source !== "messages:inbox_fetch" && data.source !== "messages:inbox_mark_read") return;
|
|
129
|
+
const key = data.source === "messages:inbox_fetch" ? "messages:inbox_history" : data.source;
|
|
130
|
+
this.rejectNext(key, /* @__PURE__ */ new Error(`${data.code ?? "error"}: ${data.message ?? "inbox request failed"}`));
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
//#endregion
|
|
135
|
+
export { NotificationsClient };
|
|
136
|
+
//# sourceMappingURL=NotificationsClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NotificationsClient.js","names":[],"sources":["../../src/NotificationsClient.ts"],"sourcesContent":["import EventEmitter from \"./EventEmitter.ts\";\nimport type { ChatClientTransport } from \"./ChatClient.ts\";\n\ntype PendingResolver<T> = {\n resolve: (value: T) => void;\n reject: (err: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Per-user inbox doc entry. Mirrors `InboxEntry` on the server. */\nexport interface InboxEntry {\n id: string;\n /** \"mention\" | \"reply\" | \"dm\" | \"system\". */\n kind: string;\n channel_doc_id: string;\n message_id?: string | null;\n sender_id?: string | null;\n sender_name?: string | null;\n /** Empty for E2E channels (server can't read body). Filled otherwise. */\n preview?: string | null;\n ts: number;\n /** Synthesized client-side from the inbox doc's `read` Y.Map. */\n read: boolean;\n}\n\nexport interface FetchInboxInput {\n before?: number;\n limit?: number;\n unread_only?: boolean;\n}\n\nexport interface MarkReadInput {\n id?: string;\n ids?: string[];\n source_id?: string;\n all?: boolean;\n}\n\n/**\n * Thin façade over the `messages:inbox_*` stateless protocol.\n *\n * Per-user notifications live as Y.Array entries on the user's inbox doc\n * (`kind = \"inbox\"`, owned by the user, child of the server root, server-only\n * writer). Real-time observation of new entries is a Y.Array observer the\n * consumer attaches via `AbracadabraProvider` on the inbox doc.\n *\n * This client handles only the request/response layer:\n * - `fetch()` issues `messages:inbox_fetch`, returns the entry list.\n * - `markRead()` issues `messages:inbox_mark_read` (id / ids / source_id /\n * all variants).\n *\n * For incoming notification observation, open an AbracadabraProvider on the\n * inbox doc and observe its `entries` Y.Array directly. The dashboard's\n * `useNotifications` composable does this.\n */\nexport class NotificationsClient extends EventEmitter {\n private readonly provider: ChatClientTransport;\n private readonly responseTimeoutMs: number;\n private readonly pending: Map<string, PendingResolver<any>[]> = new Map();\n private readonly boundOnStateless: (data: { payload: string }) => void;\n private readonly boundOnServerError: (data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }) => void;\n\n constructor(provider: ChatClientTransport, options?: { responseTimeoutMs?: number }) {\n super();\n this.provider = provider;\n this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.boundOnStateless = (data) => this.handleStateless(data.payload);\n this.boundOnServerError = (data) => this.handleServerError(data);\n this.provider.on(\"stateless\", this.boundOnStateless);\n // BaseProvider emits `serverError` for `{type:\"error\",source,code}` frames\n // instead of `stateless`. Subscribe so inbox request rejections surface.\n this.provider.on(\"serverError\", this.boundOnServerError);\n }\n\n destroy(): void {\n this.provider.off(\"stateless\", this.boundOnStateless);\n this.provider.off(\"serverError\", this.boundOnServerError);\n for (const queue of this.pending.values()) {\n for (const p of queue) {\n clearTimeout(p.timer);\n p.reject(new Error(\"NotificationsClient destroyed\"));\n }\n }\n this.pending.clear();\n this.removeAllListeners();\n }\n\n /** Fetch a slice of the calling user's inbox. Resolves with the entries. */\n fetch(input: FetchInboxInput = {}): Promise<{ entries: InboxEntry[] }> {\n const promise = this.enqueue<{ entries: InboxEntry[] }>(\"messages:inbox_history\");\n this.provider.sendStateless(\n JSON.stringify({\n type: \"messages:inbox_fetch\",\n ...(input.before !== undefined ? { before: input.before } : {}),\n ...(input.limit !== undefined ? { limit: input.limit } : {}),\n ...(input.unread_only !== undefined ? { unread_only: input.unread_only } : {}),\n }),\n );\n return promise;\n }\n\n /**\n * Mark inbox entries read. One of `id`, `ids`, `source_id`, or `all`.\n * Returns when the server has acked.\n */\n markRead(input: MarkReadInput): Promise<void> {\n const body: Record<string, unknown> = { type: \"messages:inbox_mark_read\" };\n if (input.all === true) body.all = true;\n else if (input.source_id !== undefined) body.source_id = input.source_id;\n else if (input.ids !== undefined) body.ids = input.ids;\n else if (input.id !== undefined) body.id = input.id;\n else return Promise.reject(new Error(\"markRead: one of id/ids/source_id/all required\"));\n\n const promise = this.enqueue<void>(\"messages:inbox_mark_read\");\n this.provider.sendStateless(JSON.stringify(body));\n return promise;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────────\n\n private enqueue<T>(source: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.removePending(source, entry);\n reject(new Error(`NotificationsClient: timeout waiting for ${source}`));\n }, this.responseTimeoutMs);\n const entry: PendingResolver<T> = { resolve, reject, timer };\n const queue = this.pending.get(source) ?? [];\n queue.push(entry);\n this.pending.set(source, queue);\n });\n }\n\n private removePending(source: string, entry: PendingResolver<any>): void {\n const queue = this.pending.get(source);\n if (!queue) return;\n const idx = queue.indexOf(entry);\n if (idx >= 0) queue.splice(idx, 1);\n if (queue.length === 0) this.pending.delete(source);\n }\n\n private resolveNext<T>(source: string, value: T): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.resolve(value);\n return true;\n }\n\n private rejectNext(source: string, err: Error): boolean {\n const queue = this.pending.get(source);\n if (!queue || queue.length === 0) return false;\n const next = queue.shift()!;\n if (queue.length === 0) this.pending.delete(source);\n clearTimeout(next.timer);\n next.reject(err);\n return true;\n }\n\n private handleStateless(payload: string): void {\n let parsed: any;\n try {\n parsed = JSON.parse(payload);\n } catch {\n return;\n }\n const type: unknown = parsed?.type;\n if (typeof type !== \"string\") return;\n\n if (type === \"messages:inbox_history\") {\n this.resolveNext(\"messages:inbox_history\", {\n entries: parsed.entries ?? [],\n });\n return;\n }\n if (type === \"messages:ok\" && parsed.source === \"messages:inbox_mark_read\") {\n this.resolveNext(\"messages:inbox_mark_read\", undefined);\n return;\n }\n }\n\n private handleServerError(data: {\n source: string;\n code: string;\n message: string;\n meta?: unknown;\n }): void {\n if (data.source !== \"messages:inbox_fetch\" && data.source !== \"messages:inbox_mark_read\") {\n return;\n }\n const key =\n data.source === \"messages:inbox_fetch\" ? \"messages:inbox_history\" : data.source;\n this.rejectNext(\n key,\n new Error(`${data.code ?? \"error\"}: ${data.message ?? \"inbox request failed\"}`),\n );\n }\n}\n"],"mappings":";;;AASA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;AAgD3B,IAAa,sBAAb,cAAyC,aAAa;CAYpD,YAAY,UAA+B,SAA0C;AACnF,SAAO;iCAVuD,IAAI,KAAK;AAWvE,OAAK,WAAW;AAChB,OAAK,oBAAoB,SAAS,qBAAqB;AACvD,OAAK,oBAAoB,SAAS,KAAK,gBAAgB,KAAK,QAAQ;AACpE,OAAK,sBAAsB,SAAS,KAAK,kBAAkB,KAAK;AAChE,OAAK,SAAS,GAAG,aAAa,KAAK,iBAAiB;AAGpD,OAAK,SAAS,GAAG,eAAe,KAAK,mBAAmB;;CAG1D,UAAgB;AACd,OAAK,SAAS,IAAI,aAAa,KAAK,iBAAiB;AACrD,OAAK,SAAS,IAAI,eAAe,KAAK,mBAAmB;AACzD,OAAK,MAAM,SAAS,KAAK,QAAQ,QAAQ,CACvC,MAAK,MAAM,KAAK,OAAO;AACrB,gBAAa,EAAE,MAAM;AACrB,KAAE,uBAAO,IAAI,MAAM,gCAAgC,CAAC;;AAGxD,OAAK,QAAQ,OAAO;AACpB,OAAK,oBAAoB;;;CAI3B,MAAM,QAAyB,EAAE,EAAsC;EACrE,MAAM,UAAU,KAAK,QAAmC,yBAAyB;AACjF,OAAK,SAAS,cACZ,KAAK,UAAU;GACb,MAAM;GACN,GAAI,MAAM,WAAW,SAAY,EAAE,QAAQ,MAAM,QAAQ,GAAG,EAAE;GAC9D,GAAI,MAAM,UAAU,SAAY,EAAE,OAAO,M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