@abraca/dabra 2.34.0 → 2.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2621,6 +2621,7 @@ var AbracadabraBaseProvider = class extends EventEmitter {
2621
2621
  }
2622
2622
  documentUpdateHandler(update, origin) {
2623
2623
  if (origin === this) return;
2624
+ if (!this.isAuthenticated) return;
2624
2625
  this.incrementUnsyncedChanges();
2625
2626
  this.send(UpdateMessage, {
2626
2627
  update,
@@ -2628,6 +2629,7 @@ var AbracadabraBaseProvider = class extends EventEmitter {
2628
2629
  });
2629
2630
  }
2630
2631
  awarenessUpdateHandler({ added, updated, removed }, origin) {
2632
+ if (!this.isAuthenticated) return;
2631
2633
  const changedClients = added.concat(updated).concat(removed);
2632
2634
  this.send(AwarenessMessage, {
2633
2635
  awareness: this.awareness,
@@ -13974,7 +13976,7 @@ const MNEMONIC_HKDF_SALT = /* @__PURE__ */ new TextEncoder().encode("abracadabra
13974
13976
  const MNEMONIC_HKDF_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-identity-v1");
13975
13977
  /** HKDF info string for deriving the AES-GCM seed-wrapping key from PRF output. */
13976
13978
  const SEED_WRAP_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-seed-wrap-v1");
13977
- function toBase64url$1(bytes) {
13979
+ function toBase64url$2(bytes) {
13978
13980
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
13979
13981
  }
13980
13982
  /**
@@ -14016,14 +14018,14 @@ function mnemonicToEd25519Seed(mnemonic, passphrase) {
14016
14018
  async function mnemonicToKeyPair(mnemonic, passphrase) {
14017
14019
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
14018
14020
  const publicKey = await _noble_ed25519.getPublicKeyAsync(seed);
14019
- const publicKeyB64 = toBase64url$1(publicKey);
14021
+ const publicKeyB64 = toBase64url$2(publicKey);
14020
14022
  const x25519PublicKey = ed25519.utils.toMontgomery(publicKey);
14021
14023
  return {
14022
14024
  seed,
14023
14025
  publicKey,
14024
14026
  publicKeyB64,
14025
14027
  x25519PublicKey,
14026
- x25519PublicKeyB64: toBase64url$1(x25519PublicKey)
14028
+ x25519PublicKeyB64: toBase64url$2(x25519PublicKey)
14027
14029
  };
14028
14030
  }
14029
14031
  /**
@@ -14134,10 +14136,10 @@ const PRF_SALT = new Uint8Array([
14134
14136
  207
14135
14137
  ]);
14136
14138
  const HKDF_INFO$1 = new TextEncoder().encode("abracadabra-identity-v1");
14137
- function toBase64url(bytes) {
14139
+ function toBase64url$1(bytes) {
14138
14140
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14139
14141
  }
14140
- function fromBase64url(b64) {
14142
+ function fromBase64url$1(b64) {
14141
14143
  const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14142
14144
  const padLen = (4 - padded.length % 4) % 4;
14143
14145
  const padded2 = padded + "=".repeat(padLen);
@@ -14255,9 +14257,9 @@ var CryptoIdentityKeystore = class {
14255
14257
  if (!credential) throw new Error("WebAuthn credential creation cancelled");
14256
14258
  const seed = deriveEd25519Seed(extractPrfOutput(credential));
14257
14259
  const publicKey = await _noble_ed25519.getPublicKeyAsync(seed);
14258
- const publicKeyB64 = toBase64url(publicKey);
14259
- const x25519PubB64 = toBase64url(ed25519.utils.toMontgomery(publicKey));
14260
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14260
+ const publicKeyB64 = toBase64url$1(publicKey);
14261
+ const x25519PubB64 = toBase64url$1(ed25519.utils.toMontgomery(publicKey));
14262
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14261
14263
  const db = await openDb$4();
14262
14264
  await dbPut(db, credentialIdB64, {
14263
14265
  username,
@@ -14283,8 +14285,8 @@ var CryptoIdentityKeystore = class {
14283
14285
  async sign(challengeB64, credentialIdHint) {
14284
14286
  const { seed } = await this._assertAndDerive(credentialIdHint);
14285
14287
  try {
14286
- const challengeBytes = fromBase64url(challengeB64);
14287
- return toBase64url(await _noble_ed25519.signAsync(challengeBytes, seed));
14288
+ const challengeBytes = fromBase64url$1(challengeB64);
14289
+ return toBase64url$1(await _noble_ed25519.signAsync(challengeBytes, seed));
14288
14290
  } finally {
14289
14291
  seed.fill(0);
14290
14292
  }
@@ -14369,7 +14371,7 @@ var CryptoIdentityKeystore = class {
14369
14371
  try {
14370
14372
  const all = await dbGetAll(db);
14371
14373
  if (all.length === 0) return null;
14372
- const edPub = fromBase64url(all[0].value.publicKey);
14374
+ const edPub = fromBase64url$1(all[0].value.publicKey);
14373
14375
  return ed25519.utils.toMontgomery(edPub);
14374
14376
  } finally {
14375
14377
  db.close();
@@ -14464,7 +14466,7 @@ var CryptoIdentityKeystore = class {
14464
14466
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14465
14467
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14466
14468
  wrapKey.fill(0);
14467
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14469
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14468
14470
  const db = await openDb$4();
14469
14471
  await dbPut(db, credentialIdB64, {
14470
14472
  username,
@@ -14510,7 +14512,7 @@ var CryptoIdentityKeystore = class {
14510
14512
  name: rpName
14511
14513
  },
14512
14514
  user: {
14513
- id: fromBase64url(kp.publicKeyB64),
14515
+ id: fromBase64url$1(kp.publicKeyB64),
14514
14516
  name: kp.publicKeyB64.slice(0, 16),
14515
14517
  displayName: kp.publicKeyB64.slice(0, 16)
14516
14518
  },
@@ -14534,7 +14536,7 @@ var CryptoIdentityKeystore = class {
14534
14536
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14535
14537
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14536
14538
  wrapKey.fill(0);
14537
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14539
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14538
14540
  let username = "";
14539
14541
  try {
14540
14542
  const db = await openDb$4();
@@ -14565,8 +14567,8 @@ var CryptoIdentityKeystore = class {
14565
14567
  * The caller manages the seed lifecycle (wiping on session end).
14566
14568
  */
14567
14569
  static async signWithSeed(challengeB64, seed) {
14568
- const challengeBytes = fromBase64url(challengeB64);
14569
- return toBase64url(await _noble_ed25519.signAsync(challengeBytes, seed));
14570
+ const challengeBytes = fromBase64url$1(challengeB64);
14571
+ return toBase64url$1(await _noble_ed25519.signAsync(challengeBytes, seed));
14570
14572
  }
14571
14573
  /**
14572
14574
  * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.
@@ -14575,8 +14577,8 @@ var CryptoIdentityKeystore = class {
14575
14577
  static async signWithMnemonic(mnemonic, challengeB64, passphrase) {
14576
14578
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
14577
14579
  try {
14578
- const challengeBytes = fromBase64url(challengeB64);
14579
- return toBase64url(await _noble_ed25519.signAsync(challengeBytes, seed));
14580
+ const challengeBytes = fromBase64url$1(challengeB64);
14581
+ return toBase64url$1(await _noble_ed25519.signAsync(challengeBytes, seed));
14580
14582
  } finally {
14581
14583
  seed.fill(0);
14582
14584
  }
@@ -14588,7 +14590,7 @@ var CryptoIdentityKeystore = class {
14588
14590
  async _assertAndDerive(credentialIdHint) {
14589
14591
  const allowCredentials = [];
14590
14592
  if (credentialIdHint) allowCredentials.push({
14591
- id: fromBase64url(credentialIdHint),
14593
+ id: fromBase64url$1(credentialIdHint),
14592
14594
  type: "public-key"
14593
14595
  });
14594
14596
  else try {
@@ -14608,7 +14610,7 @@ var CryptoIdentityKeystore = class {
14608
14610
  } });
14609
14611
  if (!assertion) throw new Error("WebAuthn assertion cancelled");
14610
14612
  const prfOutput = extractPrfOutput(assertion);
14611
- const credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));
14613
+ const credentialIdB64 = toBase64url$1(new Uint8Array(assertion.rawId));
14612
14614
  let stored;
14613
14615
  try {
14614
14616
  const db = await openDb$4();
@@ -14621,7 +14623,7 @@ var CryptoIdentityKeystore = class {
14621
14623
  seed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);
14622
14624
  wrapKey.fill(0);
14623
14625
  } else seed = deriveEd25519Seed(prfOutput);
14624
- const publicKeyB64 = toBase64url(await _noble_ed25519.getPublicKeyAsync(seed));
14626
+ const publicKeyB64 = toBase64url$1(await _noble_ed25519.getPublicKeyAsync(seed));
14625
14627
  try {
14626
14628
  const db = await openDb$4();
14627
14629
  const existing = await dbGet(db, credentialIdB64);
@@ -14644,6 +14646,374 @@ var CryptoIdentityKeystore = class {
14644
14646
  }
14645
14647
  };
14646
14648
 
14649
+ //#endregion
14650
+ //#region packages/provider/src/NodeIdentity.ts
14651
+ /**
14652
+ * NodeIdentity — Ed25519 identity helpers for Node-side consumers.
14653
+ *
14654
+ * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
14655
+ * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
14656
+ * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
14657
+ * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
14658
+ * the same challenge → sign → verify flow exposed by
14659
+ * {@link AbracadabraClient.loginWithKey}.
14660
+ *
14661
+ * Every one of those packages previously vendored a near-identical `crypto.ts`
14662
+ * (key-file load/create + `signChallenge`) plus a copy-pasted
14663
+ * "login → register-on-404 → re-login" block. These helpers are the single
14664
+ * shared home for both.
14665
+ *
14666
+ * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
14667
+ * touches the filesystem, and it does so via dynamic `import("node:…")` so this
14668
+ * module stays importable from browser bundles (the fs path simply isn't
14669
+ * reachable there).
14670
+ */
14671
+ _noble_ed25519.hashes.sha512 = sha512;
14672
+ _noble_ed25519.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
14673
+ function toBase64url(bytes) {
14674
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14675
+ }
14676
+ function fromBase64url(b64) {
14677
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14678
+ const padLen = (4 - padded.length % 4) % 4;
14679
+ return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) => c.charCodeAt(0));
14680
+ }
14681
+ /**
14682
+ * Sign a base64url server challenge with a 32-byte Ed25519 seed.
14683
+ * Returns a base64url signature suitable for
14684
+ * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
14685
+ */
14686
+ function signChallengeWithSeed(challengeB64, seed) {
14687
+ return toBase64url(_noble_ed25519.sign(fromBase64url(challengeB64), seed));
14688
+ }
14689
+ /**
14690
+ * Build the async `signChallenge` callback that
14691
+ * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
14692
+ * returned function around to re-authenticate after a JWT expires.
14693
+ */
14694
+ function makeChallengeSigner(keypair) {
14695
+ return (challenge) => Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
14696
+ }
14697
+ /**
14698
+ * Derive a deterministic keypair from a seed string: the same input always
14699
+ * yields the same on-server identity. Used by `@abraca/orchestrator` so a named
14700
+ * actor maps to one reproducible account across runs.
14701
+ *
14702
+ * @param salt domain-separation suffix (default `"orchestrator-salt"`, the
14703
+ * historical value — change only if you intend a different identity space).
14704
+ */
14705
+ function deterministicKeypair(seed, salt = "orchestrator-salt") {
14706
+ const privateKey = sha512(new TextEncoder().encode(`${seed}:${salt}`)).slice(0, 32);
14707
+ return {
14708
+ privateKey,
14709
+ publicKeyB64: toBase64url(_noble_ed25519.getPublicKey(privateKey))
14710
+ };
14711
+ }
14712
+ /**
14713
+ * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
14714
+ * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
14715
+ * `~/.abracadabra/<defaultFileName>`.
14716
+ *
14717
+ * Node-only: filesystem modules are loaded via dynamic import, so importing
14718
+ * this symbol in a browser bundle is safe — only *calling* it requires Node.
14719
+ */
14720
+ async function loadOrCreateKeyFile(keyPath, opts = {}) {
14721
+ const { existsSync } = await import("node:fs");
14722
+ const { readFile, writeFile, mkdir } = await import("node:fs/promises");
14723
+ const { homedir } = await import("node:os");
14724
+ const { join, dirname } = await import("node:path");
14725
+ const path = keyPath ?? join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
14726
+ if (existsSync(path)) {
14727
+ const seed = await readFile(path);
14728
+ if (seed.length !== 32) throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`);
14729
+ const privateKey = new Uint8Array(seed);
14730
+ return {
14731
+ privateKey,
14732
+ publicKeyB64: toBase64url(_noble_ed25519.getPublicKey(privateKey))
14733
+ };
14734
+ }
14735
+ const privateKey = _noble_ed25519.utils.randomSecretKey();
14736
+ const publicKeyB64 = toBase64url(_noble_ed25519.getPublicKey(privateKey));
14737
+ const dir = dirname(path);
14738
+ if (!existsSync(dir)) await mkdir(dir, {
14739
+ recursive: true,
14740
+ mode: 448
14741
+ });
14742
+ await writeFile(path, privateKey, { mode: 384 });
14743
+ opts.onCreate?.({
14744
+ path,
14745
+ publicKeyB64
14746
+ });
14747
+ return {
14748
+ privateKey,
14749
+ publicKeyB64
14750
+ };
14751
+ }
14752
+ /**
14753
+ * Authenticate `keypair` against the server, auto-registering on first run.
14754
+ *
14755
+ * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
14756
+ * — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
14757
+ * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
14758
+ * Any other error propagates. Returns the JWT.
14759
+ *
14760
+ * This is the one shared implementation of the "login → register-on-404 →
14761
+ * re-login" dance previously copy-pasted into every Node consumer's connect().
14762
+ */
14763
+ async function loginOrRegisterWithKey(client, keypair, opts = {}) {
14764
+ const sign = makeChallengeSigner(keypair);
14765
+ try {
14766
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14767
+ } catch (err) {
14768
+ const e = err;
14769
+ const status = e?.status ?? e?.response?.status;
14770
+ const msg = String(e?.message ?? "").toLowerCase();
14771
+ if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
14772
+ opts.onRegister?.();
14773
+ const username = opts.username ?? (opts.displayName ? opts.displayName.replace(/\s+/g, "-").toLowerCase() : void 0);
14774
+ await client.registerWithKey({
14775
+ publicKey: keypair.publicKeyB64,
14776
+ username,
14777
+ displayName: opts.displayName,
14778
+ deviceName: opts.deviceName,
14779
+ inviteCode: opts.inviteCode
14780
+ });
14781
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14782
+ }
14783
+ }
14784
+
14785
+ //#endregion
14786
+ //#region packages/provider/src/DocUtils.ts
14787
+ /**
14788
+ * Shared utilities for the DocumentManager ORM layer.
14789
+ *
14790
+ * These functions were previously duplicated across `mcp/src/utils.ts`,
14791
+ * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
14792
+ */
14793
+ /**
14794
+ * Wait for a provider's `synced` event with a timeout.
14795
+ * Resolves immediately if the provider is already synced.
14796
+ */
14797
+ function waitForSync(provider, timeoutMs = 15e3) {
14798
+ if (provider.isSynced) return Promise.resolve();
14799
+ return new Promise((resolve, reject) => {
14800
+ const timer = setTimeout(() => {
14801
+ provider.off("synced", handler);
14802
+ reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
14803
+ }, timeoutMs);
14804
+ function handler() {
14805
+ clearTimeout(timer);
14806
+ provider.off("synced", handler);
14807
+ resolve();
14808
+ }
14809
+ provider.on("synced", handler);
14810
+ });
14811
+ }
14812
+ /**
14813
+ * Wrap a promise with a timeout.
14814
+ */
14815
+ function withTimeout(promise, timeoutMs, message) {
14816
+ return new Promise((resolve, reject) => {
14817
+ const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
14818
+ promise.then((val) => {
14819
+ clearTimeout(timer);
14820
+ resolve(val);
14821
+ }, (err) => {
14822
+ clearTimeout(timer);
14823
+ reject(err);
14824
+ });
14825
+ });
14826
+ }
14827
+ /**
14828
+ * Normalize a document ID so the hub/root doc ID is treated as the tree root
14829
+ * (null). This lets callers pass the hub doc_id from list_spaces as
14830
+ * parentId/rootId and get the expected root-level results instead of an empty
14831
+ * set.
14832
+ */
14833
+ function normalizeRootId(id, rootDocId) {
14834
+ if (id == null) return null;
14835
+ return id === rootDocId ? null : id;
14836
+ }
14837
+ /**
14838
+ * Safely read a tree map value, converting Y.Map to plain object if needed.
14839
+ */
14840
+ function toPlain(val) {
14841
+ return val instanceof yjs.Map ? val.toJSON() : val;
14842
+ }
14843
+ /**
14844
+ * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].
14845
+ *
14846
+ * Skips non-entry keys (e.g. `":updatedAt"` timestamps), and — when `selfId`
14847
+ * is given — the space root's own self-descriptor entry (keyed by the
14848
+ * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't
14849
+ * render as a phantom first child of itself. Entry values are nested
14850
+ * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a
14851
+ * Y.Map returns undefined).
14852
+ *
14853
+ * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and
14854
+ * `@abraca/resend` previously each carried a near-identical copy.
14855
+ */
14856
+ function readEntries(treeMap, selfId) {
14857
+ const entries = [];
14858
+ treeMap.forEach((raw, id) => {
14859
+ if (selfId && id === selfId) return;
14860
+ const value = toPlain(raw);
14861
+ if (typeof value !== "object" || value === null) return;
14862
+ const v = value;
14863
+ entries.push({
14864
+ id,
14865
+ label: typeof v.label === "string" && v.label ? v.label : "Untitled",
14866
+ parentId: v.parentId ?? null,
14867
+ order: typeof v.order === "number" ? v.order : 0,
14868
+ type: typeof v.type === "string" ? v.type : void 0,
14869
+ meta: v.meta,
14870
+ createdAt: typeof v.createdAt === "number" ? v.createdAt : void 0,
14871
+ updatedAt: typeof v.updatedAt === "number" ? v.updatedAt : void 0
14872
+ });
14873
+ });
14874
+ return entries;
14875
+ }
14876
+ /**
14877
+ * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
14878
+ * re-created key (create / duplicate / restore) where no concurrent
14879
+ * writer exists, so a whole-value write is safe. `undefined` fields are
14880
+ * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
14881
+ */
14882
+ function makeEntryMap(fields) {
14883
+ const m = new yjs.Map();
14884
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
14885
+ return m;
14886
+ }
14887
+ /**
14888
+ * A label is a "placeholder" — i.e. carries no real user title — when it is
14889
+ * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
14890
+ * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
14891
+ * caught too). The whole tree-label corruption class boils down to a
14892
+ * placeholder being allowed to overwrite a real title; `patchEntry` refuses
14893
+ * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
14894
+ */
14895
+ function isPlaceholderLabel(label) {
14896
+ if (typeof label !== "string") return label == null;
14897
+ const t = label.trim();
14898
+ return t === "" || t.toLowerCase() === "untitled";
14899
+ }
14900
+ /**
14901
+ * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
14902
+ * concurrent edit to a *different* field by a peer is preserved instead
14903
+ * of being clobbered by a whole-entry write — the whole-entry-LWW fix
14904
+ * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
14905
+ *
14906
+ * - nested `Y.Map` entry → set/delete only the touched keys in place;
14907
+ * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
14908
+ * - missing entry → created from the patch (lenient; matches the prior
14909
+ * call-site behaviour of spreading `undefined`).
14910
+ *
14911
+ * A patch value of `undefined` deletes the key; `null` is written.
14912
+ * Self-transacting: it batches its writes in one `Y.Doc` transaction
14913
+ * (a safe reentrant no-op join when already inside one), so callers
14914
+ * don't need to pass or own a transaction.
14915
+ *
14916
+ * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
14917
+ * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
14918
+ * DROPPED when the entry already holds a real (non-placeholder) label —
14919
+ * regardless of which consumer (cou-sh title-sync, fs-sync rename
14920
+ * detection, MCP, table renderers, a stale snapshot) tried it. This is the
14921
+ * source-of-truth guard against the "card title silently becomes Untitled
14922
+ * / files renamed to untitled.md" corruption: a placeholder must never win
14923
+ * over a real title. Creating a brand-new entry with an empty label (e.g.
14924
+ * a fresh kanban card) is still allowed — the guard only fires when a real
14925
+ * label already exists. Pass `{ allowLabelClear: true }` to override (the
14926
+ * single legitimate "user explicitly cleared it" path).
14927
+ */
14928
+ function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
14929
+ const apply = () => {
14930
+ const raw = treeMap.get(id);
14931
+ let effectivePatch = patch;
14932
+ if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
14933
+ let existingLabel;
14934
+ if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
14935
+ else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
14936
+ else if (raw != null && typeof raw === "object") existingLabel = raw.label;
14937
+ if (!isPlaceholderLabel(existingLabel)) {
14938
+ const { label: _dropped, ...rest } = patch;
14939
+ effectivePatch = rest;
14940
+ }
14941
+ }
14942
+ if (raw instanceof yjs.Map) {
14943
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
14944
+ else raw.set(k, v);
14945
+ for (const k of removeKeys) raw.delete(k);
14946
+ return;
14947
+ }
14948
+ const merged = {
14949
+ ...raw == null ? {} : toPlain(raw),
14950
+ ...effectivePatch
14951
+ };
14952
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
14953
+ for (const k of removeKeys) delete merged[k];
14954
+ treeMap.set(id, makeEntryMap(merged));
14955
+ };
14956
+ const doc = treeMap.doc;
14957
+ if (doc) doc.transact(apply);
14958
+ else apply();
14959
+ }
14960
+
14961
+ //#endregion
14962
+ //#region packages/provider/src/NodeConnect.ts
14963
+ /**
14964
+ * Node connection helpers — shared bootstrap primitives for the Node consumers
14965
+ * (`@abraca/mcp`, `@abraca/cli`, `@abraca/orchestrator`, `@abraca/resend`).
14966
+ *
14967
+ * Each of those packages opened a synced root/space/inbox provider with the
14968
+ * exact same incantation (`new Y.Doc({ guid }) → new AbracadabraProvider({
14969
+ * disableOfflineStore, subdocLoading:'lazy' }) → waitForSync`) and selected the
14970
+ * entry space with the same "first Kind.Space, else first top-level doc" rule.
14971
+ * Both live here now so there is one implementation.
14972
+ *
14973
+ * These are deliberately small, faithful extractions — they do NOT own auth
14974
+ * (see {@link loginOrRegisterWithKey}), awareness, child-provider caching, or
14975
+ * the reconnect/heal loop. Those stay with each consumer.
14976
+ */
14977
+ /**
14978
+ * Open a fresh `AbracadabraProvider` bound to `docId` on `client` and wait for
14979
+ * its first sync. Returns the new `Y.Doc` + provider. Used for the root space
14980
+ * doc, child-space docs, and the inbox doc alike — every Node consumer opened
14981
+ * them with these exact options.
14982
+ *
14983
+ * Offline persistence is disabled (Node daemons/CLIs are online-only) and
14984
+ * subdocs load lazily.
14985
+ */
14986
+ async function openSyncedProvider(opts) {
14987
+ const doc = new yjs.Doc({ guid: opts.docId });
14988
+ const provider = new AbracadabraProvider({
14989
+ name: opts.docId,
14990
+ document: doc,
14991
+ client: opts.client,
14992
+ disableOfflineStore: true,
14993
+ subdocLoading: "lazy"
14994
+ });
14995
+ await waitForSync(provider, opts.syncTimeoutMs);
14996
+ return {
14997
+ doc,
14998
+ provider
14999
+ };
15000
+ }
15001
+ /**
15002
+ * Pick the entry-point document from a server root's top-level children: the
15003
+ * first `Kind.Space`, falling back to the first top-level doc of any kind.
15004
+ * Returns `null` when the server has no top-level documents.
15005
+ *
15006
+ * `spaces` is returned alongside so callers that track the space list (most do)
15007
+ * don't have to re-filter.
15008
+ */
15009
+ function pickEntrySpace(roots) {
15010
+ const spaces = roots.filter((d) => d.kind === Kind.Space);
15011
+ return {
15012
+ entry: spaces[0] ?? roots[0] ?? null,
15013
+ spaces
15014
+ };
15015
+ }
15016
+
14647
15017
  //#endregion
14648
15018
  //#region packages/provider/src/DocumentCache.ts
14649
15019
  const DB_VERSION$3 = 1;
@@ -15639,6 +16009,7 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15639
16009
  this.compactionInFlightTimeout = null;
15640
16010
  this.compactionDebounceTimer = null;
15641
16011
  this.destroyed = false;
16012
+ this._pendingPreAuthUpdates = [];
15642
16013
  this.docKeyManager = configuration.docKeyManager;
15643
16014
  this.keystore = configuration.keystore;
15644
16015
  this.e2eClient = configuration.client;
@@ -15719,10 +16090,27 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15719
16090
  /** Encrypt local updates before sending over WebSocket. */
15720
16091
  documentUpdateHandler(update, origin) {
15721
16092
  if (origin === this) return;
16093
+ if (!this.isAuthenticated) {
16094
+ this._pendingPreAuthUpdates.push(update);
16095
+ return;
16096
+ }
15722
16097
  this._encryptAndSend(update).catch((e) => {
15723
16098
  console.error("[E2EAbracadabraProvider] failed to encrypt update:", e);
15724
16099
  });
15725
16100
  }
16101
+ /**
16102
+ * Flush updates buffered while unauthenticated once the server confirms the
16103
+ * doc is subscribed, then resume normal live sends.
16104
+ */
16105
+ authenticatedHandler(scope) {
16106
+ super.authenticatedHandler(scope);
16107
+ if (this._pendingPreAuthUpdates.length === 0) return;
16108
+ const pending = this._pendingPreAuthUpdates;
16109
+ this._pendingPreAuthUpdates = [];
16110
+ for (const update of pending) this._encryptAndSend(update).catch((e) => {
16111
+ console.error("[E2EAbracadabraProvider] failed to flush pre-auth update:", e);
16112
+ });
16113
+ }
15726
16114
  async _encryptAndSend(update) {
15727
16115
  const key = await this.ensureDocKey();
15728
16116
  if (!key) {
@@ -15827,148 +16215,6 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15827
16215
  }
15828
16216
  };
15829
16217
 
15830
- //#endregion
15831
- //#region packages/provider/src/DocUtils.ts
15832
- /**
15833
- * Shared utilities for the DocumentManager ORM layer.
15834
- *
15835
- * These functions were previously duplicated across `mcp/src/utils.ts`,
15836
- * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
15837
- */
15838
- /**
15839
- * Wait for a provider's `synced` event with a timeout.
15840
- * Resolves immediately if the provider is already synced.
15841
- */
15842
- function waitForSync(provider, timeoutMs = 15e3) {
15843
- if (provider.isSynced) return Promise.resolve();
15844
- return new Promise((resolve, reject) => {
15845
- const timer = setTimeout(() => {
15846
- provider.off("synced", handler);
15847
- reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
15848
- }, timeoutMs);
15849
- function handler() {
15850
- clearTimeout(timer);
15851
- resolve();
15852
- }
15853
- provider.on("synced", handler);
15854
- });
15855
- }
15856
- /**
15857
- * Wrap a promise with a timeout.
15858
- */
15859
- function withTimeout(promise, timeoutMs, message) {
15860
- return new Promise((resolve, reject) => {
15861
- const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
15862
- promise.then((val) => {
15863
- clearTimeout(timer);
15864
- resolve(val);
15865
- }, (err) => {
15866
- clearTimeout(timer);
15867
- reject(err);
15868
- });
15869
- });
15870
- }
15871
- /**
15872
- * Normalize a document ID so the hub/root doc ID is treated as the tree root
15873
- * (null). This lets callers pass the hub doc_id from list_spaces as
15874
- * parentId/rootId and get the expected root-level results instead of an empty
15875
- * set.
15876
- */
15877
- function normalizeRootId(id, rootDocId) {
15878
- if (id == null) return null;
15879
- return id === rootDocId ? null : id;
15880
- }
15881
- /**
15882
- * Safely read a tree map value, converting Y.Map to plain object if needed.
15883
- */
15884
- function toPlain(val) {
15885
- return val instanceof yjs.Map ? val.toJSON() : val;
15886
- }
15887
- /**
15888
- * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
15889
- * re-created key (create / duplicate / restore) where no concurrent
15890
- * writer exists, so a whole-value write is safe. `undefined` fields are
15891
- * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
15892
- */
15893
- function makeEntryMap(fields) {
15894
- const m = new yjs.Map();
15895
- for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
15896
- return m;
15897
- }
15898
- /**
15899
- * A label is a "placeholder" — i.e. carries no real user title — when it is
15900
- * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
15901
- * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
15902
- * caught too). The whole tree-label corruption class boils down to a
15903
- * placeholder being allowed to overwrite a real title; `patchEntry` refuses
15904
- * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
15905
- */
15906
- function isPlaceholderLabel(label) {
15907
- if (typeof label !== "string") return label == null;
15908
- const t = label.trim();
15909
- return t === "" || t.toLowerCase() === "untitled";
15910
- }
15911
- /**
15912
- * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
15913
- * concurrent edit to a *different* field by a peer is preserved instead
15914
- * of being clobbered by a whole-entry write — the whole-entry-LWW fix
15915
- * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
15916
- *
15917
- * - nested `Y.Map` entry → set/delete only the touched keys in place;
15918
- * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
15919
- * - missing entry → created from the patch (lenient; matches the prior
15920
- * call-site behaviour of spreading `undefined`).
15921
- *
15922
- * A patch value of `undefined` deletes the key; `null` is written.
15923
- * Self-transacting: it batches its writes in one `Y.Doc` transaction
15924
- * (a safe reentrant no-op join when already inside one), so callers
15925
- * don't need to pass or own a transaction.
15926
- *
15927
- * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
15928
- * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
15929
- * DROPPED when the entry already holds a real (non-placeholder) label —
15930
- * regardless of which consumer (cou-sh title-sync, fs-sync rename
15931
- * detection, MCP, table renderers, a stale snapshot) tried it. This is the
15932
- * source-of-truth guard against the "card title silently becomes Untitled
15933
- * / files renamed to untitled.md" corruption: a placeholder must never win
15934
- * over a real title. Creating a brand-new entry with an empty label (e.g.
15935
- * a fresh kanban card) is still allowed — the guard only fires when a real
15936
- * label already exists. Pass `{ allowLabelClear: true }` to override (the
15937
- * single legitimate "user explicitly cleared it" path).
15938
- */
15939
- function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
15940
- const apply = () => {
15941
- const raw = treeMap.get(id);
15942
- let effectivePatch = patch;
15943
- if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
15944
- let existingLabel;
15945
- if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
15946
- else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
15947
- else if (raw != null && typeof raw === "object") existingLabel = raw.label;
15948
- if (!isPlaceholderLabel(existingLabel)) {
15949
- const { label: _dropped, ...rest } = patch;
15950
- effectivePatch = rest;
15951
- }
15952
- }
15953
- if (raw instanceof yjs.Map) {
15954
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
15955
- else raw.set(k, v);
15956
- for (const k of removeKeys) raw.delete(k);
15957
- return;
15958
- }
15959
- const merged = {
15960
- ...raw == null ? {} : toPlain(raw),
15961
- ...effectivePatch
15962
- };
15963
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
15964
- for (const k of removeKeys) delete merged[k];
15965
- treeMap.set(id, makeEntryMap(merged));
15966
- };
15967
- const doc = treeMap.doc;
15968
- if (doc) doc.transact(apply);
15969
- else apply();
15970
- }
15971
-
15972
16218
  //#endregion
15973
16219
  //#region packages/provider/src/TreeTimestamps.ts
15974
16220
  /**
@@ -21337,6 +21583,7 @@ exports.decryptChatContent = decryptChatContent;
21337
21583
  exports.decryptField = decryptField;
21338
21584
  exports.deriveIdentityDocId = deriveIdentityDocId;
21339
21585
  exports.deriveSeedWrappingKey = deriveSeedWrappingKey;
21586
+ exports.deterministicKeypair = deterministicKeypair;
21340
21587
  exports.encryptChatContent = encryptChatContent;
21341
21588
  exports.encryptField = encryptField;
21342
21589
  exports.filenameToLabel = filenameToLabel;
@@ -21344,20 +21591,27 @@ exports.foldRecords = foldRecords;
21344
21591
  exports.generateMnemonic = generateMnemonic;
21345
21592
  exports.isEncryptedContent = isEncryptedContent;
21346
21593
  exports.isPlaceholderLabel = isPlaceholderLabel;
21594
+ exports.loadOrCreateKeyFile = loadOrCreateKeyFile;
21595
+ exports.loginOrRegisterWithKey = loginOrRegisterWithKey;
21596
+ exports.makeChallengeSigner = makeChallengeSigner;
21347
21597
  exports.makeEncryptedYMap = makeEncryptedYMap;
21348
21598
  exports.makeEncryptedYText = makeEncryptedYText;
21349
21599
  exports.makeEntryMap = makeEntryMap;
21350
21600
  exports.mnemonicToEd25519Seed = mnemonicToEd25519Seed;
21351
21601
  exports.mnemonicToKeyPair = mnemonicToKeyPair;
21352
21602
  exports.normalizeRootId = normalizeRootId;
21603
+ exports.openSyncedProvider = openSyncedProvider;
21353
21604
  exports.parseFrontmatter = parseFrontmatter;
21354
21605
  exports.patchEntry = patchEntry;
21606
+ exports.pickEntrySpace = pickEntrySpace;
21355
21607
  exports.populateYDocFromMarkdown = populateYDocFromMarkdown;
21356
21608
  exports.readAuthMessage = readAuthMessage;
21357
21609
  exports.readBlocksFromFragment = readBlocksFromFragment;
21610
+ exports.readEntries = readEntries;
21358
21611
  exports.reconcileDocCover = reconcileDocCover;
21359
21612
  exports.recordFromYAny = recordFromYAny;
21360
21613
  exports.resolvePageType = resolvePageType;
21614
+ exports.signChallengeWithSeed = signChallengeWithSeed;
21361
21615
  exports.toPlain = toPlain;
21362
21616
  exports.unwrapSeed = unwrapSeed;
21363
21617
  exports.validateMnemonic = validateMnemonic;