my-durable 0.0.72 → 0.0.74

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.
Files changed (28) hide show
  1. package/README.md +2 -2
  2. package/apps/dpi-backend/API.md +1 -0
  3. package/apps/dpi-backend/src/backup.ts +18 -0
  4. package/apps/dpi-backend/src/notify-sinks.ts +104 -2
  5. package/apps/dpi-backend/src/routes.ts +10 -1
  6. package/apps/dpi-backend/src/store.ts +170 -7
  7. package/apps/dpi-backend/src/telegram.ts +176 -2
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BmxTF5DB.js +82 -0
  9. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-h81haD43.css +1 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +43 -4
  12. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +75 -42
  13. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +6 -2
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +6 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +12 -0
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +1 -1
  17. package/apps/dpi-sdk/src/api.ts +13 -1
  18. package/apps/dpi-sdk/src/client.ts +12 -5
  19. package/apps/dpi-sdk/src/models.ts +45 -2
  20. package/apps/dpi-sdk/src/node/config.ts +13 -2
  21. package/apps/dpi-sdk/src/node/drivers.ts +4 -0
  22. package/apps/dpi-tui/src/commands.ts +64 -2
  23. package/apps/dpi-tui/src/pairing.ts +2 -2
  24. package/apps/dpi-tui/src/views.ts +1 -1
  25. package/docs/host-project-checklist.md +1 -1
  26. package/package.json +1 -1
  27. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CpNu1wqa.js +0 -81
  28. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DSU1QhGO.css +0 -1
@@ -34,7 +34,7 @@
34
34
  * the tests run against fakes with zero sockets and zero real time.
35
35
  */
36
36
  import { randomBytes } from "node:crypto";
37
- import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
37
+ import { chmod, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
38
38
  import { dirname, resolve } from "node:path";
39
39
 
40
40
  /** Bumped only when the on-disk shape changes; `coerceRegistry` owns the upgrade path. */
@@ -101,6 +101,17 @@ export interface TelegramIo {
101
101
  /** Returns an unref-able handle, so the bridge never holds the event loop open. */
102
102
  setTimeout(cb: () => void, ms: number): { unref(): void };
103
103
  clearTimeout(t: { unref(): void }): void;
104
+ /**
105
+ * R18 (run-4 h3): cross-writer mutual exclusion around the registry's
106
+ * read-modify-write (daemon + dpi telegram CLI are two OS processes).
107
+ * Optional so pure in-memory fakes stay small; absent = unlocked caller.
108
+ */
109
+ /**
110
+ * Run `fn` while holding the advisory lock. `assertOwned` throws when this
111
+ * holder no longer owns the lock file (a peer stale-broke us) — the commit
112
+ * calls it immediately before writing so a stolen lock cannot lead to a write.
113
+ */
114
+ withLock?<T>(path: string, fn: (assertOwned: () => Promise<void>) => Promise<T>): Promise<T>;
104
115
  }
105
116
 
106
117
  export const defaultTelegramIo = (): TelegramIo => ({
@@ -121,6 +132,66 @@ export const defaultTelegramIo = (): TelegramIo => ({
121
132
  }
122
133
  },
123
134
  chmod: (path, mode) => chmod(path, mode),
135
+ withLock: async <T>(path: string, fn: (assertOwned: () => Promise<void>) => Promise<T>): Promise<T> => {
136
+ // Advisory lock file next to the registry. Both writers are the same OS
137
+ // user, so create-exclusive + stale-break (mtime older than 5 s — a
138
+ // crashed holder never wedges the bridge) is mutual exclusion enough.
139
+ // R19 (run-5 h3, leader-confirmed): the lock used to be ownership-blind —
140
+ // a stale-break stat→unlink raced a successor's fresh lock (forced
141
+ // interleave probe: double-entry), and the finally-unlink removed
142
+ // "whatever file is there". Every unlink now re-reads the holder nonce
143
+ // and removes the file only when it is still exactly the holder we judged.
144
+ const lockPath = `${path}.lock`;
145
+ const deadline = Date.now() + 10_000;
146
+ const nonce = `${process.pid}-${randomBytes(8).toString("hex")}`;
147
+ const lockNonce = async (): Promise<string | null> => {
148
+ try {
149
+ return (await readFile(lockPath, "utf8")).trim();
150
+ } catch {
151
+ return null; // vanished between the stat and the read — retry
152
+ }
153
+ };
154
+ for (;;) {
155
+ try {
156
+ const handle = await open(lockPath, "wx", 0o600);
157
+ await handle.write(`${nonce}\n`);
158
+ await handle.close();
159
+ break;
160
+ } catch (error) {
161
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
162
+ let age = 0;
163
+ let seen: string | null = null;
164
+ try {
165
+ age = Date.now() - (await stat(lockPath)).mtimeMs;
166
+ seen = await lockNonce();
167
+ } catch {
168
+ continue; // released between the create attempt and the stat
169
+ }
170
+ if (seen === null) continue; // gone mid-judge — retry the create
171
+ if (age > 5_000) {
172
+ // Stale candidate — break it ONLY if it is still exactly the holder
173
+ // we just judged (a successor's fresh lock must survive our unlink).
174
+ const now = await lockNonce();
175
+ if (now !== null && now === seen) await unlink(lockPath).catch(() => undefined);
176
+ continue;
177
+ }
178
+ if (Date.now() > deadline) throw new Error(`telegram registry lock busy: ${lockPath}`);
179
+ await new Promise((r) => setTimeout(r, 25));
180
+ }
181
+ }
182
+ const assertOwned = async (): Promise<void> => {
183
+ const current = await lockNonce();
184
+ if (current !== nonce)
185
+ throw new Error(`telegram registry lock lost: ${lockPath} (holder changed — refusing to write)`);
186
+ };
187
+ try {
188
+ return await fn(assertOwned);
189
+ } finally {
190
+ // Release only our own lock — never a successor's.
191
+ const current = await lockNonce();
192
+ if (current !== null && current === nonce) await unlink(lockPath).catch(() => undefined);
193
+ }
194
+ },
124
195
  exists: async (path) => {
125
196
  try {
126
197
  await stat(path);
@@ -663,11 +734,27 @@ export class TelegramBridge {
663
734
  * new bytes through the io's atomic write, then 0600.
664
735
  */
665
736
  private async persist(draft: TelegramRegistryFile): Promise<void> {
737
+ // R18 (run-4 h3): the whole read-modify-write is ONE critical section for
738
+ // every lock-respecting writer (this daemon + the dpi telegram CLI share
739
+ // defaultTelegramIo). Without the lock, a CLI commit landing between the
740
+ // CAS read and the final write is silently clobbered and a revoked binding
741
+ // resurrects (leader-probe confirmed on a0893c1-era code).
742
+ const commit = async (assertOwned?: () => Promise<void>): Promise<void> => {
666
743
  // R17 (run-3 h4): the registry has TWO writers (daemon + dpi telegram
667
744
  // CLI). Write-after-read validation: if the file's bytes changed since we
668
745
  // last saw them, our snapshot is stale — writing it would clobber the
669
746
  // foreign commit (un-spend a code, revert a /stop). Fail loudly instead.
670
- if (this.registryText !== null && (await this.io.exists(this.filePath))) {
747
+ // R18 (run-4 h3): the vanished-registry case is ALSO a foreign change —
748
+ // rewriting from memory would resurrect every revoked binding. Fail closed
749
+ // exactly like syncForeign does.
750
+ if (this.registryText !== null) {
751
+ if (!(await this.io.exists(this.filePath))) {
752
+ this.mainIsGood = false;
753
+ throw new TelegramBridgeError(
754
+ "registry_changed",
755
+ `registry vanished before commit — refusing to resurrect ${this.filePath}`,
756
+ );
757
+ }
671
758
  const current = await this.io.readFile(this.filePath);
672
759
  if (current !== this.registryText) {
673
760
  this.mainIsGood = false;
@@ -682,17 +769,104 @@ export class TelegramBridge {
682
769
  if (this.mainIsGood && (await this.io.exists(this.filePath))) {
683
770
  try {
684
771
  const previous = await this.io.readFile(this.filePath);
772
+ // R19 (run-5 h3, leader-confirmed): this re-read happens AFTER the CAS
773
+ // — if the bytes moved since the CAS, a foreign write landed inside
774
+ // our commit window and writing now would clobber it silently (the
775
+ // post-write verify only sees our own payload). Fail loudly BEFORE
776
+ // any write; the foreign bytes stay authoritative on disk.
777
+ if (this.registryText !== null && previous !== this.registryText) {
778
+ this.mainIsGood = false;
779
+ throw new TelegramBridgeError(
780
+ "registry_changed",
781
+ `registry changed between CAS and commit — foreign write preserved — refusing to clobber ${this.filePath}`,
782
+ );
783
+ }
685
784
  await this.io.writeFile(this.backupPath, previous);
686
785
  await this.io.chmod(this.backupPath, 0o600);
687
786
  } catch (error) {
787
+ if (error instanceof TelegramBridgeError) throw error;
688
788
  this.warn(`could not refresh ${this.backupPath}`, error);
689
789
  }
690
790
  }
691
791
  const payload = `${JSON.stringify(draft satisfies TelegramRegistryFile, null, 2)}\n`;
792
+ // R19 (run-5 h3, leader-confirmed HIGH): the .bak refresh above is separated
793
+ // from the write by awaited fs ops, so a NON-locking peer (operator hand-edit,
794
+ // a pre-R18 writer during the upgrade window) could land its bytes after that
795
+ // read and before our write — the post-write verify only ever compares to our
796
+ // OWN payload, so both commits reported success and the revoked binding
797
+ // survived on disk. Re-read immediately before writing: any divergence from
798
+ // the CAS baseline refuses the commit with the foreign bytes intact.
799
+ if (this.registryText !== null) {
800
+ const beforeWrite = await this.io.readFile(this.filePath);
801
+ if (beforeWrite !== this.registryText) {
802
+ this.mainIsGood = false;
803
+ throw new TelegramBridgeError(
804
+ "registry_changed",
805
+ `registry changed just before commit — foreign write preserved — refusing to clobber ${this.filePath}`,
806
+ );
807
+ }
808
+ }
809
+ // R19 cold-review MAJOR 1: a peer that stale-broke our lock and then wrote
810
+ // would otherwise be clobbered by this write while we still reported
811
+ // success. Confirm ownership FIRST — a stolen lock refuses the commit.
812
+ // (A peer that ignores the lock entirely and lands its bytes inside the
813
+ // single writeFile syscall below is a documented residual: without a kernel
814
+ // compare-and-swap no in-process code can observe that interleaving.)
815
+ if (assertOwned) {
816
+ try {
817
+ await assertOwned();
818
+ } catch (error) {
819
+ // Cold-review minor: every other refusal marks the baseline bad; keep the
820
+ // symmetry so the next sync re-reads instead of trusting memory.
821
+ this.mainIsGood = false;
822
+ throw error;
823
+ }
824
+ }
692
825
  await this.io.writeFile(this.filePath, payload);
693
826
  await this.io.chmod(this.filePath, 0o600);
827
+ // R18 (run-4 h3): the CAS above is separated from the write by several
828
+ // awaited fs ops, so a foreign write can land INSIDE our commit window.
829
+ // Verify after the write: if the bytes on disk are not exactly ours, we
830
+ // clobbered someone — restore THEIR bytes (our offset commit is safely
831
+ // re-delivered by Telegram) and fail loudly. The revoked binding stays
832
+ // revoked instead of silently resurrecting.
833
+ if (this.registryText !== null) {
834
+ try {
835
+ const after = await this.io.readFile(this.filePath);
836
+ if (after !== payload) {
837
+ // R19 (run-5 h3, leader-confirmed): the foreign bytes are ALREADY on
838
+ // disk — the old rollback rewrote them (a second blind write with
839
+ // its own clobber window). Adopt only: converge memory onto what is
840
+ // there so a stale in-memory binding cannot authorize the very next
841
+ // update through syncForeign's "still our own last write" fast path.
842
+ const foreign = coerceRegistry(JSON.parse(after), this.now());
843
+ this.adopt({ ...foreign, offset: Math.max(this.offset, foreign.offset) });
844
+ this.registryText = after;
845
+ this.mainIsGood = false;
846
+ throw new TelegramBridgeError(
847
+ "registry_changed",
848
+ `registry changed during commit; foreign write preserved — refusing to clobber ${this.filePath}`,
849
+ );
850
+ }
851
+ } catch (error) {
852
+ if (error instanceof TelegramBridgeError) throw error;
853
+ // The verify read itself failed (e.g. deleted again): treat as a
854
+ // foreign change, keep the old non-null baseline so syncForeign stays
855
+ // fail-closed, and fail loudly.
856
+ this.mainIsGood = false;
857
+ throw new TelegramBridgeError(
858
+ "registry_changed",
859
+ `registry unreadable after commit — treating as foreign change on ${this.filePath}`,
860
+ );
861
+ }
862
+ }
694
863
  this.registryText = payload;
695
864
  this.mainIsGood = true;
865
+ };
866
+ if (this.io.withLock) return this.io.withLock(this.filePath, commit);
867
+ // Fakes without a lock keep the R17 semantics (CAS + verify) — the lock is
868
+ // what closes the pre-write half of the window for the real two writers.
869
+ return commit();
696
870
  }
697
871
 
698
872
  // --------------------------------------------------------------- poll loop