@ours.network/tg-connector 0.1.8-nightly.3 → 0.1.8-nightly.5

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/connector.js CHANGED
@@ -26062,6 +26062,13 @@ function deliveryTarget(chatId, threadId, lastChat) {
26062
26062
  }
26063
26063
 
26064
26064
  // src/connector.ts
26065
+ var PKG_VERSION = (() => {
26066
+ try {
26067
+ return JSON.parse(fs3.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
26068
+ } catch {
26069
+ return "unknown";
26070
+ }
26071
+ })();
26065
26072
  var CONFIG = loadConfig();
26066
26073
  var STATE_DIR = CONFIG.stateDir;
26067
26074
  var TG_NET = {
@@ -26119,15 +26126,30 @@ function exportSigningSecret(pkt) {
26119
26126
  }
26120
26127
  function saveState(pkt, dir) {
26121
26128
  try {
26122
- const bytes = withScope((lt) => Buffer.from(pkt.readonlyTx("::actor::export_state", lt).Serialize()));
26123
- fs3.mkdirSync(dir, { recursive: true });
26124
- const tmp = `${dataPath(dir)}.tmp`;
26125
- fs3.writeFileSync(tmp, bytes);
26126
- fs3.renameSync(tmp, dataPath(dir));
26129
+ saveStateFailClosed(pkt, dir);
26127
26130
  } catch (err) {
26128
26131
  log(`[${pkt.name}] failed to save state:`, String(err));
26129
26132
  }
26130
26133
  }
26134
+ function saveStateFailClosed(pkt, dir) {
26135
+ const bytes = withScope((lt) => Buffer.from(pkt.readonlyTx("::actor::export_state", lt).Serialize()));
26136
+ fs3.mkdirSync(dir, { recursive: true });
26137
+ const tmp = `${dataPath(dir)}.tmp`;
26138
+ const fd = fs3.openSync(tmp, "w", 384);
26139
+ try {
26140
+ fs3.writeFileSync(fd, bytes);
26141
+ fs3.fsyncSync(fd);
26142
+ } finally {
26143
+ fs3.closeSync(fd);
26144
+ }
26145
+ fs3.renameSync(tmp, dataPath(dir));
26146
+ const dirFd = fs3.openSync(dir, "r");
26147
+ try {
26148
+ fs3.fsyncSync(dirFd);
26149
+ } finally {
26150
+ fs3.closeSync(dirFd);
26151
+ }
26152
+ }
26131
26153
  function renderDeferredQueues(av) {
26132
26154
  const out = [];
26133
26155
  const arr = av.Reduce("queues");
@@ -26486,7 +26508,7 @@ function activateRoute(conn) {
26486
26508
  wireHandlers(
26487
26509
  pkt,
26488
26510
  {
26489
- onSaveState: () => saveState(pkt, dir),
26511
+ onSaveState: () => saveStateFailClosed(pkt, dir),
26490
26512
  onNotify: (event, payload) => {
26491
26513
  if (event === "message_received") {
26492
26514
  process.nextTick(() => void forwardToTelegram(conn));
@@ -26645,12 +26667,24 @@ async function restoreConnection(name) {
26645
26667
  const conflict = registerRoute(conn);
26646
26668
  if (conflict) log(`[${name}] route conflict on restore: ${conflict} \u2014 left unrouted`);
26647
26669
  if (hasSavedState(dir)) {
26670
+ const preCopy = `${dataPath(dir)}.pre-${PKG_VERSION}`;
26671
+ if (!fs3.existsSync(preCopy)) {
26672
+ try {
26673
+ fs3.copyFileSync(dataPath(dir), preCopy);
26674
+ fs3.chmodSync(preCopy, 384);
26675
+ log(`[${name}] pre-migration blob retained as ${preCopy.split("/").pop()}`);
26676
+ } catch (err) {
26677
+ log(`[${name}] pre-migration retention failed (continuing):`, String(err));
26678
+ }
26679
+ }
26680
+ let imported = false;
26648
26681
  try {
26649
26682
  const buf = fs3.readFileSync(dataPath(dir));
26650
26683
  await withScopeAsync(async (lt) => {
26651
26684
  const adaptData = pkt.pw.packet.ParseValue(new Uint8Array(buf)).Attach(lt);
26652
26685
  await pkt.mutatingTx("::actor::import_state", adaptData, lt);
26653
26686
  });
26687
+ imported = true;
26654
26688
  } catch (err) {
26655
26689
  log(`[${name}] FAILED TO IMPORT SAVED STATE \u2014 continuing with the reseeded identity; surviving contacts (if the blob was partially migrated) self-heal via contact restore:`, String(err));
26656
26690
  try {
@@ -26659,6 +26693,26 @@ async function restoreConnection(name) {
26659
26693
  } catch {
26660
26694
  }
26661
26695
  }
26696
+ if (imported) {
26697
+ try {
26698
+ const st = await withScopeAsync(async (lt) => {
26699
+ const r = await pkt.mutatingTx("::a2a_messaging::commit_e2e_restore", {}, lt);
26700
+ const status = r.Reduce("status").Visualize();
26701
+ const sessions = r.Reduce("sessions").IsNil() ? "0" : r.Reduce("sessions").Visualize();
26702
+ return { status: String(status), sessions: String(sessions) };
26703
+ });
26704
+ log(`[${name}] e2e restore commit: status=${st.status} sessions=${st.sessions}`);
26705
+ } catch (err) {
26706
+ log(`[${name}] E2E RESTORE REJECTED \u2014 staged session blob failed pickle validation; discarding it, fresh account + self-heal fallback take over: ${String(err).slice(0, 260)}`);
26707
+ try {
26708
+ await withScopeAsync(async (lt) => {
26709
+ await pkt.mutatingTx("::a2a_messaging::reject_e2e_restore", {}, lt);
26710
+ });
26711
+ } catch (err2) {
26712
+ log(`[${name}] reject_e2e_restore failed (staging is transient; continuing):`, String(err2));
26713
+ }
26714
+ }
26715
+ }
26662
26716
  }
26663
26717
  const key = isCatchAll(cfg.chatId) ? "any chat" : chatKey(cfg.chatId, cfg.threadId || void 0);
26664
26718
  log(`[${name}] restored (bot ${botLabel(bot)}, ${key}${cfg.peerCid ? `, peer ${cfg.peerCid}` : ", awaiting proxy"})`);
@@ -1402,34 +1402,35 @@ application actor loads libraries
1402
1402
  // The packet-level snapshot is NOT used for upgrades: it is bound to the unit
1403
1403
  // code hash, so a new .muflo cannot load an old snapshot. This data blob is.
1404
1404
  //
1405
- // The blob stays FLAT with the historical field names — the core fields come
1406
- // from a2a_messaging::export_core_state / import_core_state, the app fields
1407
- // are composed in here — so a PRE-migration export imports unchanged.
1405
+ // Core (contact / profile / hierarchy / DR-session) state is carried WHOLE under
1406
+ // $core: export_core_state owns its OWN field set, so any field the shared core
1407
+ // adds — most importantly $e2e_sessions (the DR ratchet pickles that a manual
1408
+ // per-field projection silently DROPPED, losing messages across a reload) — rides
1409
+ // forward automatically, and the core's monitoring keys never collide with the
1410
+ // APP-level monitoring keys we still own below (they share both names AND shapes).
1411
+ // The blob stays code-independent; import_state migrates the pre-namespacing FLAT
1412
+ // shape forward (see there). Mirrors ours-mcp's actor exactly.
1408
1413
 
1409
1414
  trn readonly export_state _
1410
1415
  {
1411
- core_state = a2a_messaging::export_core_state NIL.
1412
1416
  return (
1413
1417
  $app_format_version -> 1,
1414
- $my_name -> core_state $my_name,
1415
- $contacts -> core_state $contacts,
1416
- $pending_invites -> core_state $pending_invites,
1418
+ $core -> a2a_messaging::export_core_state NIL,
1419
+ // ---- app-owned state (route inbox + files + local book + monitoring) ----
1417
1420
  $inbox -> inbox,
1418
1421
  $next_msg_seq -> next_msg_seq,
1419
1422
  $file_inbox -> file_inbox,
1420
1423
  $next_file_seq -> next_file_seq,
1421
- $peer_ads -> core_state $peer_ads,
1422
1424
  $registrar_ad -> registrar_ad,
1423
1425
  $local_auto_accept -> local_auto_accept,
1424
1426
  // Nonces are exported so a restart does not reopen the replay window
1425
1427
  // for still-fresh credentials; stale ones are purged lazily anyway.
1426
1428
  $seen_nonces -> seen_nonces,
1427
1429
  $pending_introductions -> pending_introductions,
1428
- $my_bio -> core_state $my_bio,
1429
- $delegation_cert -> core_state $delegation_cert,
1430
- $root_ad -> core_state $root_ad,
1431
- $root_profile -> core_state $root_profile,
1432
- $contact_roots -> core_state $contact_roots,
1430
+ // App-level (role->root) monitoring — a DISTINCT mechanism from core's
1431
+ // forced monitoring. Stays app-owned and top-level; it must NEVER be fed
1432
+ // into import_core_state (that would arm core's hidden monitoring_proxy,
1433
+ // which the app cannot disarm). See import_state's legacy branch.
1433
1434
  $monitoring_enabled -> monitoring_enabled,
1434
1435
  $monitoring_inbox -> monitoring_inbox,
1435
1436
  $proxy_pending -> proxy_pending,
@@ -1449,11 +1450,36 @@ application actor loads libraries
1449
1450
  if (data $app_format_version) != NIL { app_fmt -> (data $app_format_version) safe int. }
1450
1451
  abort "App state blob format_version " + (_str app_fmt) + " is newer than this code (supports up to 1) — upgrade ours-tg-connector before importing." when app_fmt > 1.
1451
1452
 
1452
- // Core fields (contacts/profile/hierarchy) — validated and restored by
1453
- // the shared library, which also replays every peer's address document
1454
- // through process_address_document so encrypted channels keep working
1455
- // after the upgrade with no re-handshake.
1456
- a2a_messaging::import_core_state data.
1453
+ // Core fields (contacts/profile/hierarchy/DR-sessions) — validated and restored
1454
+ // by the shared library, which also replays every peer's address document
1455
+ // through process_address_document so encrypted channels keep working after the
1456
+ // upgrade with no re-handshake, and parks $e2e_sessions for the staged commit
1457
+ // below. The current export namespaces core under $core, so the core owns its
1458
+ // own field set and its monitoring keys never collide with the app's. A
1459
+ // PRE-namespacing FLAT blob carries the core fields at the top level — migrate it
1460
+ // by feeding import_core_state ONLY the genuine shared fields. We deliberately
1461
+ // OMIT proxy_pending / monitoring_proxy on the legacy path: in a flat blob those
1462
+ // keys hold the APP-level monitoring state (same names AND shapes as core's), and
1463
+ // feeding them to import_core_state would arm core's hidden forced-monitoring
1464
+ // proxy — which the app can NEVER disarm. Mirrors ours-mcp's actor exactly.
1465
+ if (data $core) != NIL
1466
+ {
1467
+ a2a_messaging::import_core_state (data $core).
1468
+ }
1469
+ else
1470
+ {
1471
+ a2a_messaging::import_core_state (
1472
+ $my_name -> data $my_name,
1473
+ $contacts -> data $contacts,
1474
+ $pending_invites -> data $pending_invites,
1475
+ $peer_ads -> data $peer_ads,
1476
+ $my_bio -> data $my_bio,
1477
+ $delegation_cert -> data $delegation_cert,
1478
+ $root_ad -> data $root_ad,
1479
+ $root_profile -> data $root_profile,
1480
+ $contact_roots -> data $contact_roots
1481
+ ).
1482
+ }
1457
1483
 
1458
1484
  // The inbox + next_msg_seq are the only parts the message-lifecycle changes
1459
1485
  // touched. A pre-lifecycle blob has no $next_msg_seq and inbox entries with
@@ -104,6 +104,14 @@ library a2a_capabilities loads libraries
104
104
  // continues untouched (so the receipts-style id PAIR is not needed here).
105
105
  cap_e2e_migrate = "core.e2e.migrate".
106
106
 
107
+ // core 0.11 — e2e session self-heal (a2a_messaging e2e_rekey_request + unacked
108
+ // redrive). PROTOCOL-surface id with NO control verbs, $advertise-carried:
109
+ // "on a decode failure you may send me e2e_rekey_request and I serve a gated
110
+ // re-key". Gates the REQUESTER's send (a peer that never advertises it gets
111
+ // the readvertise_ad fallback instead — a pre-0.11 daemon must never receive
112
+ // an unknown control tx); never authz (REG-6).
113
+ cap_e2e_rekey = "core.e2e.rekey".
114
+
107
115
  // ---- secret-field sentinels (config dialect, core.configuration) ------
108
116
  // A secret field's VALUE is never echoed in plaintext: reads carry one of
109
117
  // these sentinels, and writes interpret them. "$needs_reentry" is the