@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.
@@ -2591,6 +2591,7 @@ var AbracadabraBaseProvider = class extends EventEmitter {
2591
2591
  }
2592
2592
  documentUpdateHandler(update, origin) {
2593
2593
  if (origin === this) return;
2594
+ if (!this.isAuthenticated) return;
2594
2595
  this.incrementUnsyncedChanges();
2595
2596
  this.send(UpdateMessage, {
2596
2597
  update,
@@ -2598,6 +2599,7 @@ var AbracadabraBaseProvider = class extends EventEmitter {
2598
2599
  });
2599
2600
  }
2600
2601
  awarenessUpdateHandler({ added, updated, removed }, origin) {
2602
+ if (!this.isAuthenticated) return;
2601
2603
  const changedClients = added.concat(updated).concat(removed);
2602
2604
  this.send(AwarenessMessage, {
2603
2605
  awareness: this.awareness,
@@ -13944,7 +13946,7 @@ const MNEMONIC_HKDF_SALT = /* @__PURE__ */ new TextEncoder().encode("abracadabra
13944
13946
  const MNEMONIC_HKDF_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-identity-v1");
13945
13947
  /** HKDF info string for deriving the AES-GCM seed-wrapping key from PRF output. */
13946
13948
  const SEED_WRAP_INFO = /* @__PURE__ */ new TextEncoder().encode("abracadabra-seed-wrap-v1");
13947
- function toBase64url$1(bytes) {
13949
+ function toBase64url$2(bytes) {
13948
13950
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
13949
13951
  }
13950
13952
  /**
@@ -13986,14 +13988,14 @@ function mnemonicToEd25519Seed(mnemonic, passphrase) {
13986
13988
  async function mnemonicToKeyPair(mnemonic, passphrase) {
13987
13989
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
13988
13990
  const publicKey = await ed.getPublicKeyAsync(seed);
13989
- const publicKeyB64 = toBase64url$1(publicKey);
13991
+ const publicKeyB64 = toBase64url$2(publicKey);
13990
13992
  const x25519PublicKey = ed25519.utils.toMontgomery(publicKey);
13991
13993
  return {
13992
13994
  seed,
13993
13995
  publicKey,
13994
13996
  publicKeyB64,
13995
13997
  x25519PublicKey,
13996
- x25519PublicKeyB64: toBase64url$1(x25519PublicKey)
13998
+ x25519PublicKeyB64: toBase64url$2(x25519PublicKey)
13997
13999
  };
13998
14000
  }
13999
14001
  /**
@@ -14104,10 +14106,10 @@ const PRF_SALT = new Uint8Array([
14104
14106
  207
14105
14107
  ]);
14106
14108
  const HKDF_INFO$1 = new TextEncoder().encode("abracadabra-identity-v1");
14107
- function toBase64url(bytes) {
14109
+ function toBase64url$1(bytes) {
14108
14110
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14109
14111
  }
14110
- function fromBase64url(b64) {
14112
+ function fromBase64url$1(b64) {
14111
14113
  const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14112
14114
  const padLen = (4 - padded.length % 4) % 4;
14113
14115
  const padded2 = padded + "=".repeat(padLen);
@@ -14225,9 +14227,9 @@ var CryptoIdentityKeystore = class {
14225
14227
  if (!credential) throw new Error("WebAuthn credential creation cancelled");
14226
14228
  const seed = deriveEd25519Seed(extractPrfOutput(credential));
14227
14229
  const publicKey = await ed.getPublicKeyAsync(seed);
14228
- const publicKeyB64 = toBase64url(publicKey);
14229
- const x25519PubB64 = toBase64url(ed25519.utils.toMontgomery(publicKey));
14230
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14230
+ const publicKeyB64 = toBase64url$1(publicKey);
14231
+ const x25519PubB64 = toBase64url$1(ed25519.utils.toMontgomery(publicKey));
14232
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14231
14233
  const db = await openDb$4();
14232
14234
  await dbPut(db, credentialIdB64, {
14233
14235
  username,
@@ -14253,8 +14255,8 @@ var CryptoIdentityKeystore = class {
14253
14255
  async sign(challengeB64, credentialIdHint) {
14254
14256
  const { seed } = await this._assertAndDerive(credentialIdHint);
14255
14257
  try {
14256
- const challengeBytes = fromBase64url(challengeB64);
14257
- return toBase64url(await ed.signAsync(challengeBytes, seed));
14258
+ const challengeBytes = fromBase64url$1(challengeB64);
14259
+ return toBase64url$1(await ed.signAsync(challengeBytes, seed));
14258
14260
  } finally {
14259
14261
  seed.fill(0);
14260
14262
  }
@@ -14339,7 +14341,7 @@ var CryptoIdentityKeystore = class {
14339
14341
  try {
14340
14342
  const all = await dbGetAll(db);
14341
14343
  if (all.length === 0) return null;
14342
- const edPub = fromBase64url(all[0].value.publicKey);
14344
+ const edPub = fromBase64url$1(all[0].value.publicKey);
14343
14345
  return ed25519.utils.toMontgomery(edPub);
14344
14346
  } finally {
14345
14347
  db.close();
@@ -14434,7 +14436,7 @@ var CryptoIdentityKeystore = class {
14434
14436
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14435
14437
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14436
14438
  wrapKey.fill(0);
14437
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14439
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14438
14440
  const db = await openDb$4();
14439
14441
  await dbPut(db, credentialIdB64, {
14440
14442
  username,
@@ -14480,7 +14482,7 @@ var CryptoIdentityKeystore = class {
14480
14482
  name: rpName
14481
14483
  },
14482
14484
  user: {
14483
- id: fromBase64url(kp.publicKeyB64),
14485
+ id: fromBase64url$1(kp.publicKeyB64),
14484
14486
  name: kp.publicKeyB64.slice(0, 16),
14485
14487
  displayName: kp.publicKeyB64.slice(0, 16)
14486
14488
  },
@@ -14504,7 +14506,7 @@ var CryptoIdentityKeystore = class {
14504
14506
  const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
14505
14507
  const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
14506
14508
  wrapKey.fill(0);
14507
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
14509
+ const credentialIdB64 = toBase64url$1(new Uint8Array(credential.rawId));
14508
14510
  let username = "";
14509
14511
  try {
14510
14512
  const db = await openDb$4();
@@ -14535,8 +14537,8 @@ var CryptoIdentityKeystore = class {
14535
14537
  * The caller manages the seed lifecycle (wiping on session end).
14536
14538
  */
14537
14539
  static async signWithSeed(challengeB64, seed) {
14538
- const challengeBytes = fromBase64url(challengeB64);
14539
- return toBase64url(await ed.signAsync(challengeBytes, seed));
14540
+ const challengeBytes = fromBase64url$1(challengeB64);
14541
+ return toBase64url$1(await ed.signAsync(challengeBytes, seed));
14540
14542
  }
14541
14543
  /**
14542
14544
  * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.
@@ -14545,8 +14547,8 @@ var CryptoIdentityKeystore = class {
14545
14547
  static async signWithMnemonic(mnemonic, challengeB64, passphrase) {
14546
14548
  const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
14547
14549
  try {
14548
- const challengeBytes = fromBase64url(challengeB64);
14549
- return toBase64url(await ed.signAsync(challengeBytes, seed));
14550
+ const challengeBytes = fromBase64url$1(challengeB64);
14551
+ return toBase64url$1(await ed.signAsync(challengeBytes, seed));
14550
14552
  } finally {
14551
14553
  seed.fill(0);
14552
14554
  }
@@ -14558,7 +14560,7 @@ var CryptoIdentityKeystore = class {
14558
14560
  async _assertAndDerive(credentialIdHint) {
14559
14561
  const allowCredentials = [];
14560
14562
  if (credentialIdHint) allowCredentials.push({
14561
- id: fromBase64url(credentialIdHint),
14563
+ id: fromBase64url$1(credentialIdHint),
14562
14564
  type: "public-key"
14563
14565
  });
14564
14566
  else try {
@@ -14578,7 +14580,7 @@ var CryptoIdentityKeystore = class {
14578
14580
  } });
14579
14581
  if (!assertion) throw new Error("WebAuthn assertion cancelled");
14580
14582
  const prfOutput = extractPrfOutput(assertion);
14581
- const credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));
14583
+ const credentialIdB64 = toBase64url$1(new Uint8Array(assertion.rawId));
14582
14584
  let stored;
14583
14585
  try {
14584
14586
  const db = await openDb$4();
@@ -14591,7 +14593,7 @@ var CryptoIdentityKeystore = class {
14591
14593
  seed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);
14592
14594
  wrapKey.fill(0);
14593
14595
  } else seed = deriveEd25519Seed(prfOutput);
14594
- const publicKeyB64 = toBase64url(await ed.getPublicKeyAsync(seed));
14596
+ const publicKeyB64 = toBase64url$1(await ed.getPublicKeyAsync(seed));
14595
14597
  try {
14596
14598
  const db = await openDb$4();
14597
14599
  const existing = await dbGet(db, credentialIdB64);
@@ -14614,6 +14616,374 @@ var CryptoIdentityKeystore = class {
14614
14616
  }
14615
14617
  };
14616
14618
 
14619
+ //#endregion
14620
+ //#region packages/provider/src/NodeIdentity.ts
14621
+ /**
14622
+ * NodeIdentity — Ed25519 identity helpers for Node-side consumers.
14623
+ *
14624
+ * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
14625
+ * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
14626
+ * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
14627
+ * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
14628
+ * the same challenge → sign → verify flow exposed by
14629
+ * {@link AbracadabraClient.loginWithKey}.
14630
+ *
14631
+ * Every one of those packages previously vendored a near-identical `crypto.ts`
14632
+ * (key-file load/create + `signChallenge`) plus a copy-pasted
14633
+ * "login → register-on-404 → re-login" block. These helpers are the single
14634
+ * shared home for both.
14635
+ *
14636
+ * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
14637
+ * touches the filesystem, and it does so via dynamic `import("node:…")` so this
14638
+ * module stays importable from browser bundles (the fs path simply isn't
14639
+ * reachable there).
14640
+ */
14641
+ ed.hashes.sha512 = sha512;
14642
+ ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
14643
+ function toBase64url(bytes) {
14644
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
14645
+ }
14646
+ function fromBase64url(b64) {
14647
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
14648
+ const padLen = (4 - padded.length % 4) % 4;
14649
+ return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) => c.charCodeAt(0));
14650
+ }
14651
+ /**
14652
+ * Sign a base64url server challenge with a 32-byte Ed25519 seed.
14653
+ * Returns a base64url signature suitable for
14654
+ * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
14655
+ */
14656
+ function signChallengeWithSeed(challengeB64, seed) {
14657
+ return toBase64url(ed.sign(fromBase64url(challengeB64), seed));
14658
+ }
14659
+ /**
14660
+ * Build the async `signChallenge` callback that
14661
+ * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
14662
+ * returned function around to re-authenticate after a JWT expires.
14663
+ */
14664
+ function makeChallengeSigner(keypair) {
14665
+ return (challenge) => Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
14666
+ }
14667
+ /**
14668
+ * Derive a deterministic keypair from a seed string: the same input always
14669
+ * yields the same on-server identity. Used by `@abraca/orchestrator` so a named
14670
+ * actor maps to one reproducible account across runs.
14671
+ *
14672
+ * @param salt domain-separation suffix (default `"orchestrator-salt"`, the
14673
+ * historical value — change only if you intend a different identity space).
14674
+ */
14675
+ function deterministicKeypair(seed, salt = "orchestrator-salt") {
14676
+ const privateKey = sha512(new TextEncoder().encode(`${seed}:${salt}`)).slice(0, 32);
14677
+ return {
14678
+ privateKey,
14679
+ publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
14680
+ };
14681
+ }
14682
+ /**
14683
+ * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
14684
+ * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
14685
+ * `~/.abracadabra/<defaultFileName>`.
14686
+ *
14687
+ * Node-only: filesystem modules are loaded via dynamic import, so importing
14688
+ * this symbol in a browser bundle is safe — only *calling* it requires Node.
14689
+ */
14690
+ async function loadOrCreateKeyFile(keyPath, opts = {}) {
14691
+ const { existsSync } = await import("node:fs");
14692
+ const { readFile, writeFile, mkdir } = await import("node:fs/promises");
14693
+ const { homedir } = await import("node:os");
14694
+ const { join, dirname } = await import("node:path");
14695
+ const path = keyPath ?? join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
14696
+ if (existsSync(path)) {
14697
+ const seed = await readFile(path);
14698
+ if (seed.length !== 32) throw new Error(`Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`);
14699
+ const privateKey = new Uint8Array(seed);
14700
+ return {
14701
+ privateKey,
14702
+ publicKeyB64: toBase64url(ed.getPublicKey(privateKey))
14703
+ };
14704
+ }
14705
+ const privateKey = ed.utils.randomSecretKey();
14706
+ const publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));
14707
+ const dir = dirname(path);
14708
+ if (!existsSync(dir)) await mkdir(dir, {
14709
+ recursive: true,
14710
+ mode: 448
14711
+ });
14712
+ await writeFile(path, privateKey, { mode: 384 });
14713
+ opts.onCreate?.({
14714
+ path,
14715
+ publicKeyB64
14716
+ });
14717
+ return {
14718
+ privateKey,
14719
+ publicKeyB64
14720
+ };
14721
+ }
14722
+ /**
14723
+ * Authenticate `keypair` against the server, auto-registering on first run.
14724
+ *
14725
+ * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
14726
+ * — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
14727
+ * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
14728
+ * Any other error propagates. Returns the JWT.
14729
+ *
14730
+ * This is the one shared implementation of the "login → register-on-404 →
14731
+ * re-login" dance previously copy-pasted into every Node consumer's connect().
14732
+ */
14733
+ async function loginOrRegisterWithKey(client, keypair, opts = {}) {
14734
+ const sign = makeChallengeSigner(keypair);
14735
+ try {
14736
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14737
+ } catch (err) {
14738
+ const e = err;
14739
+ const status = e?.status ?? e?.response?.status;
14740
+ const msg = String(e?.message ?? "").toLowerCase();
14741
+ if (!(status === 404 || status === 422 || status === 401 && /not registered|user not found|no such user/.test(msg))) throw err;
14742
+ opts.onRegister?.();
14743
+ const username = opts.username ?? (opts.displayName ? opts.displayName.replace(/\s+/g, "-").toLowerCase() : void 0);
14744
+ await client.registerWithKey({
14745
+ publicKey: keypair.publicKeyB64,
14746
+ username,
14747
+ displayName: opts.displayName,
14748
+ deviceName: opts.deviceName,
14749
+ inviteCode: opts.inviteCode
14750
+ });
14751
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
14752
+ }
14753
+ }
14754
+
14755
+ //#endregion
14756
+ //#region packages/provider/src/DocUtils.ts
14757
+ /**
14758
+ * Shared utilities for the DocumentManager ORM layer.
14759
+ *
14760
+ * These functions were previously duplicated across `mcp/src/utils.ts`,
14761
+ * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
14762
+ */
14763
+ /**
14764
+ * Wait for a provider's `synced` event with a timeout.
14765
+ * Resolves immediately if the provider is already synced.
14766
+ */
14767
+ function waitForSync(provider, timeoutMs = 15e3) {
14768
+ if (provider.isSynced) return Promise.resolve();
14769
+ return new Promise((resolve, reject) => {
14770
+ const timer = setTimeout(() => {
14771
+ provider.off("synced", handler);
14772
+ reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
14773
+ }, timeoutMs);
14774
+ function handler() {
14775
+ clearTimeout(timer);
14776
+ provider.off("synced", handler);
14777
+ resolve();
14778
+ }
14779
+ provider.on("synced", handler);
14780
+ });
14781
+ }
14782
+ /**
14783
+ * Wrap a promise with a timeout.
14784
+ */
14785
+ function withTimeout(promise, timeoutMs, message) {
14786
+ return new Promise((resolve, reject) => {
14787
+ const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
14788
+ promise.then((val) => {
14789
+ clearTimeout(timer);
14790
+ resolve(val);
14791
+ }, (err) => {
14792
+ clearTimeout(timer);
14793
+ reject(err);
14794
+ });
14795
+ });
14796
+ }
14797
+ /**
14798
+ * Normalize a document ID so the hub/root doc ID is treated as the tree root
14799
+ * (null). This lets callers pass the hub doc_id from list_spaces as
14800
+ * parentId/rootId and get the expected root-level results instead of an empty
14801
+ * set.
14802
+ */
14803
+ function normalizeRootId(id, rootDocId) {
14804
+ if (id == null) return null;
14805
+ return id === rootDocId ? null : id;
14806
+ }
14807
+ /**
14808
+ * Safely read a tree map value, converting Y.Map to plain object if needed.
14809
+ */
14810
+ function toPlain(val) {
14811
+ return val instanceof Y.Map ? val.toJSON() : val;
14812
+ }
14813
+ /**
14814
+ * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].
14815
+ *
14816
+ * Skips non-entry keys (e.g. `":updatedAt"` timestamps), and — when `selfId`
14817
+ * is given — the space root's own self-descriptor entry (keyed by the
14818
+ * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't
14819
+ * render as a phantom first child of itself. Entry values are nested
14820
+ * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a
14821
+ * Y.Map returns undefined).
14822
+ *
14823
+ * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and
14824
+ * `@abraca/resend` previously each carried a near-identical copy.
14825
+ */
14826
+ function readEntries(treeMap, selfId) {
14827
+ const entries = [];
14828
+ treeMap.forEach((raw, id) => {
14829
+ if (selfId && id === selfId) return;
14830
+ const value = toPlain(raw);
14831
+ if (typeof value !== "object" || value === null) return;
14832
+ const v = value;
14833
+ entries.push({
14834
+ id,
14835
+ label: typeof v.label === "string" && v.label ? v.label : "Untitled",
14836
+ parentId: v.parentId ?? null,
14837
+ order: typeof v.order === "number" ? v.order : 0,
14838
+ type: typeof v.type === "string" ? v.type : void 0,
14839
+ meta: v.meta,
14840
+ createdAt: typeof v.createdAt === "number" ? v.createdAt : void 0,
14841
+ updatedAt: typeof v.updatedAt === "number" ? v.updatedAt : void 0
14842
+ });
14843
+ });
14844
+ return entries;
14845
+ }
14846
+ /**
14847
+ * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
14848
+ * re-created key (create / duplicate / restore) where no concurrent
14849
+ * writer exists, so a whole-value write is safe. `undefined` fields are
14850
+ * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
14851
+ */
14852
+ function makeEntryMap(fields) {
14853
+ const m = new Y.Map();
14854
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
14855
+ return m;
14856
+ }
14857
+ /**
14858
+ * A label is a "placeholder" — i.e. carries no real user title — when it is
14859
+ * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
14860
+ * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
14861
+ * caught too). The whole tree-label corruption class boils down to a
14862
+ * placeholder being allowed to overwrite a real title; `patchEntry` refuses
14863
+ * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
14864
+ */
14865
+ function isPlaceholderLabel(label) {
14866
+ if (typeof label !== "string") return label == null;
14867
+ const t = label.trim();
14868
+ return t === "" || t.toLowerCase() === "untitled";
14869
+ }
14870
+ /**
14871
+ * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
14872
+ * concurrent edit to a *different* field by a peer is preserved instead
14873
+ * of being clobbered by a whole-entry write — the whole-entry-LWW fix
14874
+ * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
14875
+ *
14876
+ * - nested `Y.Map` entry → set/delete only the touched keys in place;
14877
+ * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
14878
+ * - missing entry → created from the patch (lenient; matches the prior
14879
+ * call-site behaviour of spreading `undefined`).
14880
+ *
14881
+ * A patch value of `undefined` deletes the key; `null` is written.
14882
+ * Self-transacting: it batches its writes in one `Y.Doc` transaction
14883
+ * (a safe reentrant no-op join when already inside one), so callers
14884
+ * don't need to pass or own a transaction.
14885
+ *
14886
+ * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
14887
+ * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
14888
+ * DROPPED when the entry already holds a real (non-placeholder) label —
14889
+ * regardless of which consumer (cou-sh title-sync, fs-sync rename
14890
+ * detection, MCP, table renderers, a stale snapshot) tried it. This is the
14891
+ * source-of-truth guard against the "card title silently becomes Untitled
14892
+ * / files renamed to untitled.md" corruption: a placeholder must never win
14893
+ * over a real title. Creating a brand-new entry with an empty label (e.g.
14894
+ * a fresh kanban card) is still allowed — the guard only fires when a real
14895
+ * label already exists. Pass `{ allowLabelClear: true }` to override (the
14896
+ * single legitimate "user explicitly cleared it" path).
14897
+ */
14898
+ function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
14899
+ const apply = () => {
14900
+ const raw = treeMap.get(id);
14901
+ let effectivePatch = patch;
14902
+ if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
14903
+ let existingLabel;
14904
+ if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
14905
+ else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
14906
+ else if (raw != null && typeof raw === "object") existingLabel = raw.label;
14907
+ if (!isPlaceholderLabel(existingLabel)) {
14908
+ const { label: _dropped, ...rest } = patch;
14909
+ effectivePatch = rest;
14910
+ }
14911
+ }
14912
+ if (raw instanceof Y.Map) {
14913
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
14914
+ else raw.set(k, v);
14915
+ for (const k of removeKeys) raw.delete(k);
14916
+ return;
14917
+ }
14918
+ const merged = {
14919
+ ...raw == null ? {} : toPlain(raw),
14920
+ ...effectivePatch
14921
+ };
14922
+ for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
14923
+ for (const k of removeKeys) delete merged[k];
14924
+ treeMap.set(id, makeEntryMap(merged));
14925
+ };
14926
+ const doc = treeMap.doc;
14927
+ if (doc) doc.transact(apply);
14928
+ else apply();
14929
+ }
14930
+
14931
+ //#endregion
14932
+ //#region packages/provider/src/NodeConnect.ts
14933
+ /**
14934
+ * Node connection helpers — shared bootstrap primitives for the Node consumers
14935
+ * (`@abraca/mcp`, `@abraca/cli`, `@abraca/orchestrator`, `@abraca/resend`).
14936
+ *
14937
+ * Each of those packages opened a synced root/space/inbox provider with the
14938
+ * exact same incantation (`new Y.Doc({ guid }) → new AbracadabraProvider({
14939
+ * disableOfflineStore, subdocLoading:'lazy' }) → waitForSync`) and selected the
14940
+ * entry space with the same "first Kind.Space, else first top-level doc" rule.
14941
+ * Both live here now so there is one implementation.
14942
+ *
14943
+ * These are deliberately small, faithful extractions — they do NOT own auth
14944
+ * (see {@link loginOrRegisterWithKey}), awareness, child-provider caching, or
14945
+ * the reconnect/heal loop. Those stay with each consumer.
14946
+ */
14947
+ /**
14948
+ * Open a fresh `AbracadabraProvider` bound to `docId` on `client` and wait for
14949
+ * its first sync. Returns the new `Y.Doc` + provider. Used for the root space
14950
+ * doc, child-space docs, and the inbox doc alike — every Node consumer opened
14951
+ * them with these exact options.
14952
+ *
14953
+ * Offline persistence is disabled (Node daemons/CLIs are online-only) and
14954
+ * subdocs load lazily.
14955
+ */
14956
+ async function openSyncedProvider(opts) {
14957
+ const doc = new Y.Doc({ guid: opts.docId });
14958
+ const provider = new AbracadabraProvider({
14959
+ name: opts.docId,
14960
+ document: doc,
14961
+ client: opts.client,
14962
+ disableOfflineStore: true,
14963
+ subdocLoading: "lazy"
14964
+ });
14965
+ await waitForSync(provider, opts.syncTimeoutMs);
14966
+ return {
14967
+ doc,
14968
+ provider
14969
+ };
14970
+ }
14971
+ /**
14972
+ * Pick the entry-point document from a server root's top-level children: the
14973
+ * first `Kind.Space`, falling back to the first top-level doc of any kind.
14974
+ * Returns `null` when the server has no top-level documents.
14975
+ *
14976
+ * `spaces` is returned alongside so callers that track the space list (most do)
14977
+ * don't have to re-filter.
14978
+ */
14979
+ function pickEntrySpace(roots) {
14980
+ const spaces = roots.filter((d) => d.kind === Kind.Space);
14981
+ return {
14982
+ entry: spaces[0] ?? roots[0] ?? null,
14983
+ spaces
14984
+ };
14985
+ }
14986
+
14617
14987
  //#endregion
14618
14988
  //#region packages/provider/src/DocumentCache.ts
14619
14989
  const DB_VERSION$3 = 1;
@@ -15600,6 +15970,7 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15600
15970
  this.compactionInFlightTimeout = null;
15601
15971
  this.compactionDebounceTimer = null;
15602
15972
  this.destroyed = false;
15973
+ this._pendingPreAuthUpdates = [];
15603
15974
  this.docKeyManager = configuration.docKeyManager;
15604
15975
  this.keystore = configuration.keystore;
15605
15976
  this.e2eClient = configuration.client;
@@ -15680,10 +16051,27 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15680
16051
  /** Encrypt local updates before sending over WebSocket. */
15681
16052
  documentUpdateHandler(update, origin) {
15682
16053
  if (origin === this) return;
16054
+ if (!this.isAuthenticated) {
16055
+ this._pendingPreAuthUpdates.push(update);
16056
+ return;
16057
+ }
15683
16058
  this._encryptAndSend(update).catch((e) => {
15684
16059
  console.error("[E2EAbracadabraProvider] failed to encrypt update:", e);
15685
16060
  });
15686
16061
  }
16062
+ /**
16063
+ * Flush updates buffered while unauthenticated once the server confirms the
16064
+ * doc is subscribed, then resume normal live sends.
16065
+ */
16066
+ authenticatedHandler(scope) {
16067
+ super.authenticatedHandler(scope);
16068
+ if (this._pendingPreAuthUpdates.length === 0) return;
16069
+ const pending = this._pendingPreAuthUpdates;
16070
+ this._pendingPreAuthUpdates = [];
16071
+ for (const update of pending) this._encryptAndSend(update).catch((e) => {
16072
+ console.error("[E2EAbracadabraProvider] failed to flush pre-auth update:", e);
16073
+ });
16074
+ }
15687
16075
  async _encryptAndSend(update) {
15688
16076
  const key = await this.ensureDocKey();
15689
16077
  if (!key) {
@@ -15788,148 +16176,6 @@ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraPro
15788
16176
  }
15789
16177
  };
15790
16178
 
15791
- //#endregion
15792
- //#region packages/provider/src/DocUtils.ts
15793
- /**
15794
- * Shared utilities for the DocumentManager ORM layer.
15795
- *
15796
- * These functions were previously duplicated across `mcp/src/utils.ts`,
15797
- * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
15798
- */
15799
- /**
15800
- * Wait for a provider's `synced` event with a timeout.
15801
- * Resolves immediately if the provider is already synced.
15802
- */
15803
- function waitForSync(provider, timeoutMs = 15e3) {
15804
- if (provider.isSynced) return Promise.resolve();
15805
- return new Promise((resolve, reject) => {
15806
- const timer = setTimeout(() => {
15807
- provider.off("synced", handler);
15808
- reject(/* @__PURE__ */ new Error(`Sync timed out after ${timeoutMs}ms`));
15809
- }, timeoutMs);
15810
- function handler() {
15811
- clearTimeout(timer);
15812
- resolve();
15813
- }
15814
- provider.on("synced", handler);
15815
- });
15816
- }
15817
- /**
15818
- * Wrap a promise with a timeout.
15819
- */
15820
- function withTimeout(promise, timeoutMs, message) {
15821
- return new Promise((resolve, reject) => {
15822
- const timer = setTimeout(() => reject(new Error(message ?? `Operation timed out after ${timeoutMs}ms`)), timeoutMs);
15823
- promise.then((val) => {
15824
- clearTimeout(timer);
15825
- resolve(val);
15826
- }, (err) => {
15827
- clearTimeout(timer);
15828
- reject(err);
15829
- });
15830
- });
15831
- }
15832
- /**
15833
- * Normalize a document ID so the hub/root doc ID is treated as the tree root
15834
- * (null). This lets callers pass the hub doc_id from list_spaces as
15835
- * parentId/rootId and get the expected root-level results instead of an empty
15836
- * set.
15837
- */
15838
- function normalizeRootId(id, rootDocId) {
15839
- if (id == null) return null;
15840
- return id === rootDocId ? null : id;
15841
- }
15842
- /**
15843
- * Safely read a tree map value, converting Y.Map to plain object if needed.
15844
- */
15845
- function toPlain(val) {
15846
- return val instanceof Y.Map ? val.toJSON() : val;
15847
- }
15848
- /**
15849
- * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
15850
- * re-created key (create / duplicate / restore) where no concurrent
15851
- * writer exists, so a whole-value write is safe. `undefined` fields are
15852
- * omitted; `null` is kept (a real value, e.g. top-level `parentId`).
15853
- */
15854
- function makeEntryMap(fields) {
15855
- const m = new Y.Map();
15856
- for (const [k, v] of Object.entries(fields)) if (v !== void 0) m.set(k, v);
15857
- return m;
15858
- }
15859
- /**
15860
- * A label is a "placeholder" — i.e. carries no real user title — when it is
15861
- * empty/whitespace, null/undefined, or the literal `"Untitled"` sentinel
15862
- * (case-insensitive, so `"untitled"` from a `labelToFilename` round-trip is
15863
- * caught too). The whole tree-label corruption class boils down to a
15864
- * placeholder being allowed to overwrite a real title; `patchEntry` refuses
15865
- * exactly that. Mirrors cou-sh's `isEmptyTreeLabel`.
15866
- */
15867
- function isPlaceholderLabel(label) {
15868
- if (typeof label !== "string") return label == null;
15869
- const t = label.trim();
15870
- return t === "" || t.toLowerCase() === "untitled";
15871
- }
15872
- /**
15873
- * Patch an EXISTING entry's fields per-key on its nested `Y.Map`, so a
15874
- * concurrent edit to a *different* field by a peer is preserved instead
15875
- * of being clobbered by a whole-entry write — the whole-entry-LWW fix
15876
- * (audit ⑦), the mirror of the Rust provider's `with_entry_mut`.
15877
- *
15878
- * - nested `Y.Map` entry → set/delete only the touched keys in place;
15879
- * - legacy opaque (plain-object) entry → migrated once to a `Y.Map`;
15880
- * - missing entry → created from the patch (lenient; matches the prior
15881
- * call-site behaviour of spreading `undefined`).
15882
- *
15883
- * A patch value of `undefined` deletes the key; `null` is written.
15884
- * Self-transacting: it batches its writes in one `Y.Doc` transaction
15885
- * (a safe reentrant no-op join when already inside one), so callers
15886
- * don't need to pass or own a transaction.
15887
- *
15888
- * ── NO-DESTROY LABEL INVARIANT ──────────────────────────────────────────
15889
- * A `label` patch that is a placeholder (empty/whitespace/"Untitled") is
15890
- * DROPPED when the entry already holds a real (non-placeholder) label —
15891
- * regardless of which consumer (cou-sh title-sync, fs-sync rename
15892
- * detection, MCP, table renderers, a stale snapshot) tried it. This is the
15893
- * source-of-truth guard against the "card title silently becomes Untitled
15894
- * / files renamed to untitled.md" corruption: a placeholder must never win
15895
- * over a real title. Creating a brand-new entry with an empty label (e.g.
15896
- * a fresh kanban card) is still allowed — the guard only fires when a real
15897
- * label already exists. Pass `{ allowLabelClear: true }` to override (the
15898
- * single legitimate "user explicitly cleared it" path).
15899
- */
15900
- function patchEntry(treeMap, id, patch, removeKeys = [], opts = {}) {
15901
- const apply = () => {
15902
- const raw = treeMap.get(id);
15903
- let effectivePatch = patch;
15904
- if (!opts.allowLabelClear && Object.hasOwn(patch, "label") && isPlaceholderLabel(patch.label)) {
15905
- let existingLabel;
15906
- if (raw != null && typeof raw.get === "function") existingLabel = raw.get("label");
15907
- else if (raw != null && typeof raw.toJSON === "function") existingLabel = raw.toJSON()?.label;
15908
- else if (raw != null && typeof raw === "object") existingLabel = raw.label;
15909
- if (!isPlaceholderLabel(existingLabel)) {
15910
- const { label: _dropped, ...rest } = patch;
15911
- effectivePatch = rest;
15912
- }
15913
- }
15914
- if (raw instanceof Y.Map) {
15915
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) raw.delete(k);
15916
- else raw.set(k, v);
15917
- for (const k of removeKeys) raw.delete(k);
15918
- return;
15919
- }
15920
- const merged = {
15921
- ...raw == null ? {} : toPlain(raw),
15922
- ...effectivePatch
15923
- };
15924
- for (const [k, v] of Object.entries(effectivePatch)) if (v === void 0) delete merged[k];
15925
- for (const k of removeKeys) delete merged[k];
15926
- treeMap.set(id, makeEntryMap(merged));
15927
- };
15928
- const doc = treeMap.doc;
15929
- if (doc) doc.transact(apply);
15930
- else apply();
15931
- }
15932
-
15933
16179
  //#endregion
15934
16180
  //#region packages/provider/src/TreeTimestamps.ts
15935
16181
  /**
@@ -21186,5 +21432,5 @@ var DocumentManager = class {
21186
21432
  };
21187
21433
 
21188
21434
  //#endregion
21189
- 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, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, parseFrontmatter, patchEntry, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, reconcileDocCover, recordFromYAny, resolvePageType, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
21435
+ 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 };
21190
21436
  //# sourceMappingURL=abracadabra-provider.esm.js.map