cautpartener / client / src / public / mailbox-io.ts
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/**
 * Public-plane mailbox transport (docs/PROTOCOL.md §1-3): plain HTTPS
 * deposit/replay of PLAINTEXT signed docs and unixfs blocks — no OrbitDB, no
 * encryption, no mesh. Reuses the lib's MailboxClient (deposit) with the
 * shared app-scoped open-mint bearer (core/app-mailbox-auth.ts); backward
 * paging via `before=` is public-plane-only, so the GET lives here instead of
 * the frozen lib.
 *
 * Envelope prefixes (disjoint from the private plane's 0x01/0x02):
 *   0x10 | cid.bytes | Signed bytes      signed public doc (§3)
 *   0x11 | cid.bytes | block bytes       public unixfs/raw block (images)
 *
 * `before=` paging convention (docs/PROTOCOL.md §6, empirically verified
 * against the live node 2026-08-22; mirrored by e2e/mailbox-stub.mjs):
 *   GET ?limit=N&before=<seq>  → the NEWEST N messages with seq < before,
 *                                ascending, has_more = older ones remain
 *   GET ?limit=N&before=       → the OLDEST window (forward!), NOT the newest —
 *                                a backward walk must START with the constant
 *                                MAX_BEFORE (max uint64) to get the newest page
 */

import { CID } from "multiformats/cid";
import { fromB64, type Bytes } from "../lib/crypto";
import type { MailboxConfig } from "../lib/descriptor";
import { type MailboxAuth, MailboxClient, type DepositResult, type ReplayMessage, type ReplayPage } from "../lib/mailbox";
import { appMailboxAuth } from "../core/app-mailbox-auth";
import { mailboxConfig } from "../core/rendezvous";

export const ENV_DOC = 0x10;
export const ENV_BLOCK = 0x11;

const PAGE_LIMIT = 100;
const MAX_PAGES = 20;

/**
 * First-page cursor for a backward walk (§6): max uint64. The node treats an
 * EMPTY `before=` as "oldest window forward", so the newest window must be
 * requested with a cursor above every real seq. This constant is the only
 * literal cursor — real seqs are opaque and never parsed client-side.
 */
export const MAX_BEFORE = "18446744073709551615";

// ---- envelopes ----------------------------------------------------------------

export interface PublicEnvelope {
  type: typeof ENV_DOC | typeof ENV_BLOCK;
  cid: CID;
  body: Bytes;
  /** The full raw envelope — re-deposited verbatim when re-seeding. */
  raw: Bytes;
}

/** Build one deposit envelope: prefix | cid.bytes | body. */
export function buildEnvelope(type: number, cid: CID, body: Uint8Array): Bytes {
  const out = new Uint8Array(1 + cid.bytes.length + body.length);
  out[0] = type;
  out.set(cid.bytes, 1);
  out.set(body, 1 + cid.bytes.length);
  return out;
}

/** Parse one replayed payload; null for anything that isn't a public envelope. */
export function parseEnvelope(payloadB64: string): PublicEnvelope | null {
  try {
    const raw = fromB64(payloadB64);
    if (raw.length < 2 || (raw[0] !== ENV_DOC && raw[0] !== ENV_BLOCK)) return null;
    const [cid, body] = CID.decodeFirst(raw.subarray(1));
    return { type: raw[0] as PublicEnvelope["type"], cid, body: new Uint8Array(body) as Bytes, raw };
  } catch {
    return null;
  }
}

/** Re-hash a 0x11 block body against its envelope cid (sha2-256 only). */
export async function verifyBlock(env: PublicEnvelope): Promise<boolean> {
  if (env.cid.multihash.code !== 0x12) return false;
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", env.body as BufferSource));
  const want = env.cid.multihash.digest;
  if (digest.length !== want.length) return false;
  let diff = 0;
  for (let i = 0; i < digest.length; i++) diff |= digest[i] ^ want[i];
  return diff === 0;
}

// ---- the room transport --------------------------------------------------------

export interface WalkResult {
  /** ≥1 page answered — false means the mailbox was unreachable. */
  reached: boolean;
  /** The walk saw the room's oldest message (history fully covered). */
  complete: boolean;
  /** The visitor stopped the walk early. */
  stopped: boolean;
  pages: number;
  latestSeq: string | null;
}

export class PublicRoom {
  readonly roomId: string;
  #client: MailboxClient;
  #auth: MailboxAuth;
  #base: string;

  private constructor(roomId: string, mailbox: MailboxConfig) {
    this.roomId = roomId;
    this.#auth = appMailboxAuth(mailbox.credsUrl);
    this.#client = new MailboxClient(mailbox.baseUrl, roomId, this.#auth);
    this.#base = `${mailbox.baseUrl.replace(/\/$/, "")}/rooms/${encodeURIComponent(roomId)}/messages`;
  }

  /** Null when no mailbox endpoint is configured (offline mirror). */
  static open(roomId: string, mailbox: MailboxConfig | null = mailboxConfig()): PublicRoom | null {
    return mailbox ? new PublicRoom(roomId, mailbox) : null;
  }

  /** Deposit a signed public doc under the 0x10 envelope. */
  depositDoc(signed: { cid: CID; bytes: Uint8Array }): Promise<DepositResult> {
    return this.#client.deposit(buildEnvelope(ENV_DOC, signed.cid, signed.bytes));
  }

  /** Deposit a public block (avatar/image bytes) under the 0x11 envelope. */
  depositBlock(cid: CID, block: Uint8Array): Promise<DepositResult> {
    return this.#client.deposit(buildEnvelope(ENV_BLOCK, cid, block));
  }

  /** Re-deposit a replayed envelope verbatim (re-seeding — dedup-free). */
  depositRaw(raw: Uint8Array): Promise<DepositResult> {
    return this.#client.deposit(raw);
  }

  /** Forward page (after=cursor) — lib semantics; M5 refresh cursors. */
  replayForward(cursor: string | null, limit = PAGE_LIMIT): ReturnType<MailboxClient["replay"]> {
    return this.#client.replay(cursor, limit);
  }

  /**
   * One backward page: `before=<seq>` → the newest window strictly older than
   * seq (use MAX_BEFORE for the first page — an EMPTY `before=` would return
   * the OLDEST window forward instead). Null on any transport failure.
   */
  async pageBefore(before: string, limit = PAGE_LIMIT): Promise<ReplayPage | null> {
    const qs = `?limit=${limit}&before=${encodeURIComponent(before)}`;
    for (let attempt = 0; attempt < 2; attempt++) {
      let token: string;
      try {
        token = await this.#auth.get();
      } catch {
        return null;
      }
      let res: Response;
      try {
        res = await fetch(this.#base + qs, {
          headers: { authorization: `Bearer ${token}` },
          signal: AbortSignal.timeout(20_000),
        });
      } catch {
        return null;
      }
      if ((res.status === 401 || res.status === 403) && attempt === 0) {
        this.#auth.invalidate();
        continue;
      }
      if (!res.ok) return null;
      try {
        const b = (await res.json()) as {
          messages?: ReplayMessage[];
          has_more?: boolean;
          oldest_seq?: string;
          latest_seq?: string;
        };
        return {
          messages: Array.isArray(b.messages) ? b.messages : [],
          hasMore: !!b.has_more,
          oldestSeq: b.oldest_seq ?? null,
          latestSeq: b.latest_seq ?? null,
        };
      } catch {
        return null;
      }
    }
    return null;
  }

  /**
   * Backward walk from the latest message: visits messages NEWEST-FIRST, one
   * `before=` page at a time, within a hard page budget (spam defense, §6).
   * The first page uses MAX_BEFORE (the newest window — never an empty
   * `before=`, which the node answers with the OLDEST window); every following
   * page keeps before = the oldest seq seen so far. The visitor may return
   * true to stop early (e.g. profile + mod found).
   */
  async walkBackward(
    visit: (m: ReplayMessage) => Promise<boolean | void> | boolean | void,
    opts: { pageLimit?: number; maxPages?: number } = {},
  ): Promise<WalkResult> {
    const pageLimit = opts.pageLimit ?? PAGE_LIMIT;
    const maxPages = opts.maxPages ?? MAX_PAGES;
    const result: WalkResult = { reached: false, complete: false, stopped: false, pages: 0, latestSeq: null };
    let before = MAX_BEFORE;
    while (result.pages < maxPages) {
      const page = await this.pageBefore(before, pageLimit);
      if (page === null) break;
      result.reached = true;
      result.pages++;
      result.latestSeq ??= page.latestSeq;
      if (page.messages.length === 0) {
        result.complete = true;
        break;
      }
      for (let i = page.messages.length - 1; i >= 0; i--) {
        if ((await visit(page.messages[i])) === true) {
          result.stopped = true;
          return result;
        }
      }
      if (!page.hasMore) {
        result.complete = true;
        break;
      }
      before = page.messages[0].seq;
    }
    return result;
  }
}

// ---- small per-room cache (auth tokens are per-room; don't re-mint per call) ---

const roomCache = new Map<string, PublicRoom>();

export function publicRoom(roomId: string): PublicRoom | null {
  const cached = roomCache.get(roomId);
  if (cached) return cached;
  const room = PublicRoom.open(roomId);
  if (room) {
    if (roomCache.size >= 64) roomCache.clear(); // bound; rebuilt on demand
    roomCache.set(roomId, room);
  }
  return room;
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git