cautpartener / client / src / public / profile-service.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/**
 * Public profiles (docs/PROTOCOL.md §6): publish / republish / resolve.
 *
 * OWN profile: the editing source of truth is the home-log `profile-src` op
 * (LWW singleton, §4) so edits sync across devices; the PUBLIC §3 profile doc
 * is derived from that source at publish time. Publish bumps `seq`, signs and
 * deposits the doc (0x10) plus avatar blocks (0x11) into the OWN profileRoom.
 * Every app open re-deposits the current profile + mod + avatar blocks —
 * server-side SHA-256 dedup makes that free, and it re-arms the mailbox TTL.
 *
 * AVATAR CHUNKING (kept deliberately simple): avatar bytes ≤128 KiB (§3).
 * When they fit one mailbox frame (≤ maxMessageKb−1 KiB) the avatar is ONE
 * 0x11 raw block and profile.avatar.cid is its raw CID. Otherwise the bytes
 * split into ≤(maxMessageKb−1) KiB raw chunks (≤3 given 64 KiB frames), each
 * its own 0x11 block, plus a tiny dag-cbor manifest { v:1, chunks:[CID…] }
 * deposited as a 0x11 block; profile.avatar.cid is the MANIFEST cid (dag-cbor
 * codec tells the resolver which case it holds). Avatar bytes are cached in
 * localStorage so re-deposits work offline-first; a fresh device that synced
 * profile-src but not the bytes republishes doc+mod only (visitor re-seeding
 * keeps the blocks alive).
 *
 * RESOLVE (§6): page the target's profileRoom BACKWARD (before=), keep the
 * highest valid (seq, ts) profile + mod doc; page budget 20 → honest
 * "indisponibil — posibil spam". Results cache in a localStorage LRU (~50)
 * with a stale flag; `source` says whether the mailbox or the cache answered.
 */

import { decode as cborDecode, encode as cborEncode } from "@ipld/dag-cbor";
import { CID } from "multiformats/cid";
import { sha256 } from "multiformats/hashes/sha2";
import { nsKey, RuntimeLimits } from "../config";
import {
  clampRestrictedSection,
  encodeRestrictedProfile,
  isEmptyRestrictedSection,
  type RestrictedSectionSrc,
} from "../core/audience";
import { myXIdentity } from "../core/contacts";
import { sanitizeName, type ModSrcOp, type ProfileSrcOp } from "../core/home-log";
import { decodeWithinBounds } from "../core/media";
import { Session } from "../core/session";
import { fromB64, toB64, type Bytes } from "../lib/crypto";
import { parseEnvelope, publicRoom, verifyBlock, ENV_BLOCK, ENV_DOC } from "./mailbox-io";
import {
  sanitizeText,
  signDoc,
  verifyDoc,
  AVATAR_MAX_BYTES,
  BIO_MAX,
  DAG_CBOR_CODE,
  RAW_CODE,
  SEALED_SECTIONS_MAX,
  type AvatarRef,
  type ModDoc,
  type ProfileDoc,
  type SealedSectionRef,
} from "./public-doc";
import { profileRoom } from "./public-rooms";

// ---- own profile source --------------------------------------------------------

export interface ProfileSource {
  name: string;
  bio: string;
  county: string;
  categories: string[];
  commentPolicy: "open" | "off";
  avatar?: AvatarRef;
  /** Audience-restricted sections (M5b) — PLAINTEXT, home-log only (§4). */
  restricted?: RestrictedSectionSrc[];
  /**
   * The sealed boxes derived from `restricted` at the last publish. Stored in
   * the op (not re-derived) so boot republishes stay byte-identical per seq —
   * a fresh random-IV seal would mint a new doc CID on every open and defeat
   * the server-side dedup the §6 republish contract relies on.
   */
  sealed?: SealedSectionRef[];
}

export function emptySource(): ProfileSource {
  return { name: "", bio: "", county: "", categories: [], commentPolicy: "open" };
}

function isRestrictedSrc(v: unknown): v is RestrictedSectionSrc {
  return !!v && typeof v === "object" && typeof (v as RestrictedSectionSrc).gid === "string";
}

/** The current profile source from the folded home log (defaults when unset). */
export function mySource(): { src: ProfileSource; op: ProfileSrcOp | null } {
  const op = Session.selfroom?.state.profileSrc ?? null;
  const d = (op?.doc ?? {}) as Partial<ProfileSource>;
  return {
    op,
    src: {
      name: typeof d.name === "string" ? d.name : "",
      bio: typeof d.bio === "string" ? d.bio : "",
      county: typeof d.county === "string" ? d.county : "",
      categories: Array.isArray(d.categories) ? d.categories.filter((c): c is string => typeof c === "string") : [],
      commentPolicy: d.commentPolicy === "off" ? "off" : "open",
      ...(d.avatar && typeof d.avatar === "object" ? { avatar: d.avatar as AvatarRef } : {}),
      ...(Array.isArray(d.restricted) ? { restricted: d.restricted.filter(isRestrictedSrc) } : {}),
      ...(Array.isArray(d.sealed) ? { sealed: d.sealed as SealedSectionRef[] } : {}),
    },
  };
}

// ---- avatar bytes (local cache + chunking) -------------------------------------

const AVATAR_KEY = nsKey("avatar-src");

interface StoredAvatar {
  cid: string;
  b64: string;
}

function loadAvatarBytes(cid: string): Bytes | null {
  try {
    const raw = localStorage.getItem(AVATAR_KEY);
    if (!raw) return null;
    const s = JSON.parse(raw) as Partial<StoredAvatar>;
    if (s.cid !== cid || typeof s.b64 !== "string") return null;
    return fromB64(s.b64);
  } catch {
    return null;
  }
}

function saveAvatarBytes(cid: string, bytes: Bytes): void {
  try {
    localStorage.setItem(AVATAR_KEY, JSON.stringify({ cid, b64: toB64(bytes) } satisfies StoredAvatar));
  } catch {}
}

function clearAvatarBytes(): void {
  try {
    localStorage.removeItem(AVATAR_KEY);
  } catch {}
}

function chunkSize(): number {
  return (RuntimeLimits.maxMessageKb - 1) * 1024;
}

/** Data URL of the OWN avatar from the local bytes cache (editor preview). */
export function myAvatarUrl(): string | null {
  const { src } = mySource();
  if (!src.avatar) return null;
  const bytes = loadAvatarBytes(src.avatar.cid);
  return bytes ? `data:${src.avatar.mime};base64,${toB64(bytes)}` : null;
}

export interface AvatarBlocks {
  root: CID;
  blocks: { cid: CID; bytes: Bytes }[];
}

/**
 * Split arbitrary public bytes into 0x11 blocks: one raw block when they fit
 * a mailbox frame, else raw chunks + a dag-cbor { v:1, chunks:[CID…] }
 * manifest whose cid is the root (the root cid's codec tells the resolver
 * which case it holds). Shared by avatars (M4) and post images (M5).
 */
export async function packBlocks(bytes: Bytes): Promise<AvatarBlocks> {
  const size = chunkSize();
  if (bytes.length <= size) {
    const cid = CID.create(1, RAW_CODE, await sha256.digest(bytes));
    return { root: cid, blocks: [{ cid, bytes }] };
  }
  const blocks: { cid: CID; bytes: Bytes }[] = [];
  const chunkCids: CID[] = [];
  for (let off = 0; off < bytes.length; off += size) {
    const chunk = bytes.slice(off, off + size);
    const cid = CID.create(1, RAW_CODE, await sha256.digest(chunk));
    blocks.push({ cid, bytes: chunk });
    chunkCids.push(cid);
  }
  const manifest = cborEncode({ v: 1, chunks: chunkCids }) as Bytes;
  const root = CID.create(1, DAG_CBOR_CODE, await sha256.digest(manifest));
  blocks.push({ cid: root, bytes: manifest });
  return { root, blocks };
}

/** Single-block or chunks+manifest split, capped at the §3 avatar limit. */
export async function avatarBlocks(bytes: Bytes): Promise<AvatarBlocks> {
  if (bytes.length > AVATAR_MAX_BYTES) throw new Error("avatar over 128 KiB");
  return packBlocks(bytes);
}

/**
 * Reassemble packBlocks output from replayed 0x11 blocks, hash-verifying
 * every block against its cid. `expectedBytes` must match exactly when the
 * caller knows it (null = unknown, e.g. thumbnails whose length is not in
 * the doc); `maxBytes`/`maxChunks` bound the assembly against forged
 * manifests either way. Null on any failure — never throws on wire input.
 */
export async function assembleBlocks(
  rootCidStr: string,
  expectedBytes: number | null,
  maxBytes: number,
  maxChunks: number,
  blocks: Map<string, Bytes>,
): Promise<Bytes | null> {
  try {
    const root = CID.parse(rootCidStr);
    const rootBytes = blocks.get(rootCidStr);
    if (!rootBytes) return null;
    if (rootBytes.length > maxBytes) return null;
    if (!(await verifyBlock({ type: ENV_BLOCK, cid: root, body: rootBytes, raw: rootBytes }))) return null;
    if (root.code === RAW_CODE) return expectedBytes === null || rootBytes.length === expectedBytes ? rootBytes : null;
    // manifest case
    const m = cborDecode(rootBytes) as { v?: unknown; chunks?: unknown };
    if (!m || m.v !== 1 || !Array.isArray(m.chunks) || m.chunks.length === 0 || m.chunks.length > maxChunks) return null;
    const parts: Bytes[] = [];
    let total = 0;
    for (const c of m.chunks) {
      const cid = CID.asCID(c);
      if (!cid) return null;
      const part = blocks.get(cid.toString());
      if (!part) return null;
      if (!(await verifyBlock({ type: ENV_BLOCK, cid, body: part, raw: part }))) return null;
      total += part.length;
      if (total > maxBytes) return null;
      parts.push(part);
    }
    if (expectedBytes !== null && total !== expectedBytes) return null;
    const out = new Uint8Array(total);
    let off = 0;
    for (const p of parts) {
      out.set(p, off);
      off += p.length;
    }
    return out;
  } catch {
    return null;
  }
}

/** Reassemble avatar bytes from replayed 0x11 blocks (hash-verified). */
function assembleAvatar(ref: AvatarRef, blocks: Map<string, Bytes>): Promise<Bytes | null> {
  return assembleBlocks(ref.cid, ref.bytes, AVATAR_MAX_BYTES, 8, blocks);
}

// ---- publish status (profile tab UI) -------------------------------------------

const STATUS_KEY = nsKey("pub-status");

export interface PublishStatus {
  lastPublishAt: number;
  lastResult: "ok" | "failed";
  lastBootRepublishAt: number;
}

export function publishStatus(): PublishStatus | null {
  try {
    const raw = localStorage.getItem(STATUS_KEY);
    return raw ? (JSON.parse(raw) as PublishStatus) : null;
  } catch {
    return null;
  }
}

function recordStatus(patch: Partial<PublishStatus>): void {
  const prev = publishStatus() ?? { lastPublishAt: 0, lastResult: "ok" as const, lastBootRepublishAt: 0 };
  try {
    localStorage.setItem(STATUS_KEY, JSON.stringify({ ...prev, ...patch }));
  } catch {}
}

// ---- publish --------------------------------------------------------------------

export interface AvatarInput {
  bytes: Bytes;
  w: number;
  h: number;
  mime: string;
}

export type PublishOutcome = { ok: true } | { ok: false; reason: "invalid" | "offline" | "deposit" };

function stampAbove(prevTs: number | undefined): number {
  return Math.max(Date.now(), (prevTs ?? 0) + 1);
}

/**
 * Merge `patch` over the current source, bump seq, append profile-src to the
 * home log, then sign + deposit the derived public doc (+ avatar blocks +
 * current mod doc) into the own profileRoom. `avatarChange`: undefined = keep,
 * null = remove, AvatarInput = new avatar.
 */
export async function publishProfile(
  patch: Partial<ProfileSource>,
  avatarChange?: AvatarInput | null,
): Promise<PublishOutcome> {
  const id = Session.identity;
  const room = Session.selfroom;
  if (!id || !room) return { ok: false, reason: "offline" };

  const { src, op } = mySource();
  const next: ProfileSource = { ...src, ...patch };
  next.name = sanitizeName(next.name);
  next.bio = sanitizeText(next.bio, BIO_MAX);
  next.categories = [...new Set(next.categories)].slice(0, 8);
  if (!next.name || !next.county) return { ok: false, reason: "invalid" };

  // restricted sections (M5b): clamp, drop empties / inactive groups / dup
  // gids, then seal each under its group's CURRENT epoch key. The sealed
  // boxes are stored in the op so republishes stay deterministic per seq.
  const restricted: RestrictedSectionSrc[] = [];
  const seenGids = new Set<string>();
  for (const raw of next.restricted ?? []) {
    if (!isRestrictedSrc(raw) || seenGids.has(raw.gid)) continue;
    if (room.state.groups.get(raw.gid)?.status !== "active") continue;
    const sec = clampRestrictedSection(raw);
    if (isEmptyRestrictedSection(sec)) continue;
    seenGids.add(raw.gid);
    restricted.push({ gid: raw.gid, ...sec });
    if (restricted.length >= SEALED_SECTIONS_MAX) break;
  }
  if (restricted.length > 0) next.restricted = restricted;
  else delete next.restricted;
  delete next.sealed;
  if (restricted.length > 0) {
    const audience = Session.audience;
    if (!audience) return { ok: false, reason: "offline" }; // selfroom stack still booting
    const sealed: SealedSectionRef[] = [];
    for (const sec of restricted) {
      const ref = await audience.seal(sec.gid, encodeRestrictedProfile(sec)).catch(() => null);
      if (ref) sealed.push(ref);
    }
    if (sealed.length > 0) next.sealed = sealed;
  }

  let avatarUpload: AvatarBlocks | null = null;
  if (avatarChange === null) {
    delete next.avatar;
    clearAvatarBytes();
  } else if (avatarChange) {
    avatarUpload = await avatarBlocks(avatarChange.bytes);
    next.avatar = {
      cid: avatarUpload.root.toString(),
      mime: avatarChange.mime === "image/jpeg" ? "image/jpeg" : "image/webp",
      w: avatarChange.w,
      h: avatarChange.h,
      bytes: avatarChange.bytes.length,
    };
    saveAvatarBytes(next.avatar.cid, avatarChange.bytes);
  }

  const seq = (op?.seq ?? 0) + 1;
  const ts = stampAbove(op?.ts);
  await room.appendHomeOp({ t: "profile-src", ts, seq, doc: next as unknown as Record<string, unknown> });
  if (next.name !== room.state.settings.name) await room.setSettings({ name: next.name }).catch(() => {});

  const deposited = await depositCurrent(avatarUpload);
  recordStatus({ lastPublishAt: Date.now(), lastResult: deposited ? "ok" : "failed" });
  return deposited ? { ok: true } : { ok: false, reason: "deposit" };
}

/** Bump the mod source (hide cids / block pubs) and deposit the §3 mod doc. */
export async function publishMod(patch: { hide?: string[]; block?: string[] }): Promise<boolean> {
  const id = Session.identity;
  const room = Session.selfroom;
  if (!id || !room) return false;
  const prev = room.state.modSrc;
  const hidden = [...new Set([...(prev?.hidden ?? []), ...(patch.hide ?? [])])].slice(-500);
  const blocked = [...new Set([...(prev?.blocked ?? []), ...(patch.block ?? [])])].slice(-200);
  const op: ModSrcOp = { t: "mod-src", ts: stampAbove(prev?.ts), seq: (prev?.seq ?? 0) + 1, hidden, blocked };
  await room.appendHomeOp(op);
  return depositCurrent(null);
}

/** Build the §3 profile doc from the CURRENT source (deterministic per seq). */
async function buildOwnDocs(): Promise<{ profile: ProfileDoc | null; mod: ModDoc | null }> {
  const id = Session.identity;
  const room = Session.selfroom;
  if (!id || !room) return { profile: null, mod: null };
  const { src, op } = mySource();
  let profile: ProfileDoc | null = null;
  if (op && src.name && src.county) {
    const x = await myXIdentity(id.identity, id.seed, src.name);
    profile = {
      ts: op.ts,
      seq: op.seq,
      name: x.name,
      bio: src.bio,
      county: src.county,
      categories: src.categories,
      ...(src.avatar ? { avatar: src.avatar } : {}),
      xPub: x.xPub,
      xSig: x.xSig,
      commentPolicy: src.commentPolicy,
      ...(src.sealed && src.sealed.length > 0 ? { sealed: src.sealed } : {}),
    } as ProfileDoc;
  }
  const m = room.state.modSrc;
  const mod: ModDoc | null = m ? { ts: m.ts, seq: m.seq, hidden: m.hidden, blocked: m.blocked } : null;
  return { profile, mod };
}

/**
 * Sign + deposit the CURRENT profile + mod docs (+ avatar blocks) into the
 * own profileRoom. Same-seq rebuilds produce byte-identical docs (Ed25519 and
 * dag-cbor are deterministic), so the server dedups re-deposits and only the
 * TTL is re-armed. Returns false when nothing could be deposited.
 */
async function depositCurrent(freshAvatar: AvatarBlocks | null): Promise<boolean> {
  const id = Session.identity;
  if (!id) return false;
  const { profile, mod } = await buildOwnDocs();
  if (!profile && !mod) return true; // nothing to publish yet
  const room = publicRoom(await profileRoom(id.identity.publicKeyB64));
  if (!room) return false;
  let allOk = true;
  if (profile) {
    const signed = await signDoc(id.identity, "profile", profile);
    const r = await room.depositDoc(signed);
    if (!r.ok) allOk = false;
    // avatar blocks: freshly encoded ones, else the locally cached bytes
    let blocks = freshAvatar;
    if (!blocks && profile.avatar) {
      const bytes = loadAvatarBytes(profile.avatar.cid);
      if (bytes) blocks = await avatarBlocks(bytes);
    }
    if (blocks) {
      for (const b of blocks.blocks) {
        const r2 = await room.depositBlock(b.cid, b.bytes);
        if (!r2.ok) allOk = false;
      }
    }
  }
  if (mod) {
    const signed = await signDoc(id.identity, "mod", mod);
    const r = await room.depositDoc(signed);
    if (!r.ok) allOk = false;
  }
  return allOk;
}

/**
 * Boot republish (§6): re-deposit the current profile + mod + avatar blocks.
 * Dedup makes it free; it re-arms the room TTL. Called jittered from boot.
 */
export async function republishOwn(): Promise<void> {
  const ok = await depositCurrent(null);
  recordStatus({ lastBootRepublishAt: Date.now(), ...(ok ? {} : { lastResult: "failed" as const }) });
}

/**
 * A group was re-keyed (member removed, M5b): when the profile carries a
 * restricted section for that group, re-publish it — the section re-seals
 * under the NEW epoch with a bumped seq, so the removed member loses the
 * CURRENT profile section too, not only future edits. (Posts already sealed
 * stay under their old epochs: immutable docs, removal ≠ retraction, §7.)
 */
export async function republishAfterRekey(gid: string): Promise<void> {
  const { src } = mySource();
  if (!(src.restricted ?? []).some((s) => s.gid === gid)) return;
  await publishProfile({});
}

// ---- resolve --------------------------------------------------------------------

export interface ResolvedProfile {
  state: "ok";
  source: "mailbox" | "cache";
  /** Cache answers are always flagged stale-capable; UI shows the banner. */
  stale: boolean;
  pub: string;
  profile: ProfileDoc;
  hidden: Set<string>;
  blocked: Set<string>;
  avatarUrl: string | null;
}

export interface UnresolvedProfile {
  state: "none";
  /** empty = room reached but no valid doc; budget = §6 spam budget exceeded; net = mailbox unreachable. */
  reason: "empty" | "budget" | "net";
}

export type ProfileResult = ResolvedProfile | UnresolvedProfile;

const CACHE_KEY = nsKey("pub-cache");
const CACHE_MAX = 50;
const CACHE_AVATAR_MAX = 65_536; // only small avatars are cached (quota care)

interface CacheEntry {
  at: number;
  profile: ProfileDoc;
  hidden: string[];
  blocked: string[];
  avatar?: string; // data URL
}

function loadCache(): Record<string, CacheEntry> {
  try {
    const raw = localStorage.getItem(CACHE_KEY);
    return raw ? (JSON.parse(raw) as Record<string, CacheEntry>) : {};
  } catch {
    return {};
  }
}

function saveCache(cache: Record<string, CacheEntry>): void {
  const entries = Object.entries(cache).sort((a, b) => b[1].at - a[1].at);
  try {
    localStorage.setItem(CACHE_KEY, JSON.stringify(Object.fromEntries(entries.slice(0, CACHE_MAX))));
  } catch {}
}

function fromCache(pub: string): ResolvedProfile | null {
  const entry = loadCache()[pub];
  if (!entry) return null;
  return {
    state: "ok",
    source: "cache",
    stale: true,
    pub,
    profile: entry.profile,
    hidden: new Set(entry.hidden),
    blocked: new Set(entry.blocked),
    avatarUrl: entry.avatar ?? null,
  };
}

function dataUrl(mime: string, bytes: Bytes): string {
  return `data:${mime};base64,${toB64(bytes)}`;
}

/**
 * Cache-only profile lookup (no network) — the feed uses it to fill author
 * headers instantly before deciding whether a mailbox resolve is worth it.
 */
export function cachedProfile(pub: string): ResolvedProfile | null {
  return fromCache(pub);
}

/**
 * Resolve one public profile from its mailbox rooms (§6). Backward walk,
 * highest valid (seq, ts) profile + mod win; page budget 20. Falls back to
 * the local cache (marked stale) when the mailbox can't answer.
 */
export async function resolveProfile(pub: string): Promise<ProfileResult> {
  let roomId: string;
  try {
    roomId = await profileRoom(pub);
  } catch {
    return { state: "none", reason: "empty" };
  }
  const room = publicRoom(roomId);
  if (!room) return fromCache(pub) ?? { state: "none", reason: "net" };

  let best: ProfileDoc | null = null;
  let bestMod: ModDoc | null = null;
  const blocks = new Map<string, Bytes>();

  const walk = await room.walkBackward(async (m) => {
    const env = parseEnvelope(m.payload);
    if (!env) return;
    if (env.type === ENV_BLOCK) {
      // hash-verify BEFORE taking the cid slot (bound transient memory). The
      // avatar room is open and replay is first-write-wins, so junk deposited
      // under the real avatar cid must never occupy the slot and block the
      // genuine block from assembling (§6 — see feed-service #ingest).
      const bc = env.cid.toString();
      if (blocks.size < 24 && !blocks.has(bc) && (await verifyBlock(env))) blocks.set(bc, env.body);
      return;
    }
    if (env.type !== ENV_DOC) return;
    const v = await verifyDoc(env.body, { kinds: ["profile", "mod"], pub, cid: env.cid });
    if (!v) return;
    if (v.kind === "profile") {
      const d = v.doc as ProfileDoc;
      if (!best || d.seq > best.seq || (d.seq === best.seq && d.ts > best.ts)) best = d;
    } else {
      const d = v.doc as ModDoc;
      if (!bestMod || d.seq > bestMod.seq || (d.seq === bestMod.seq && d.ts > bestMod.ts)) bestMod = d;
    }
  });

  if (!walk.reached) return fromCache(pub) ?? { state: "none", reason: "net" };
  const winner = best as ProfileDoc | null;
  const winnerMod = bestMod as ModDoc | null;
  if (!winner) {
    // room reached but no valid profile within the budget — honest states
    const cached = fromCache(pub);
    if (cached) return cached;
    return { state: "none", reason: walk.complete ? "empty" : "budget" };
  }

  let avatarUrl: string | null = null;
  if (winner.avatar) {
    const bytes = await assembleAvatar(winner.avatar, blocks);
    // foreign bytes: same decode-bomb guard as chat images — the doc's w/h
    // only describe the layout box; the ACTUAL decode must stay bounded
    if (bytes && (await decodeWithinBounds(new Blob([bytes as BlobPart], { type: winner.avatar.mime })))) {
      avatarUrl = dataUrl(winner.avatar.mime, bytes);
    }
  }

  // refresh the LRU cache
  const cache = loadCache();
  cache[pub] = {
    at: Date.now(),
    profile: winner,
    hidden: winnerMod?.hidden ?? [],
    blocked: winnerMod?.blocked ?? [],
    ...(avatarUrl && avatarUrl.length <= CACHE_AVATAR_MAX * 1.4 ? { avatar: avatarUrl } : {}),
  };
  saveCache(cache);

  return {
    state: "ok",
    source: "mailbox",
    stale: false,
    pub,
    profile: winner,
    hidden: new Set(winnerMod?.hidden ?? []),
    blocked: new Set(winnerMod?.blocked ?? []),
    avatarUrl,
  };
}

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