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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650 | /**
* Matching (P2, docs/PROTOCOL.md §2/§3/§5c): pool cards + likes as sealed
* dead-drops, hidden until mutual.
*
* Cards: signed `cp-card|v1` docs in poolRoom(pool) — opt-in "caut partener
* pentru <categorie> în <județ>". LWW per (pub, pool) by (seq, ts, cid);
* `retired: true` withdraws through the same slot. The §3 cert (with the
* profile name) rides along so a liker can seal to the author's verified
* X25519 key without any prior contact.
*
* Likes: a 0x12 envelope — `0x12 | dagCbor(Wrap)` — deposited into the
* TARGET's inboxRoom. The Wrap is a lib wrapbox sealed box to the target's
* certified xPub with roomId = inboxRoom(target) (AAD
* "v1|<inboxRoom(target)>|wrap|<targetPub>", the board pattern). Payload
* (dag-cbor): { v:1, kind:"like", pool, token, roomSecret, ts } — it
* deliberately does NOT name the sender. A received like is therefore
* ANONYMOUS until mutual:
* token = mutualToken(A,B) = b64url(HKDF(ikm = X25519(xA,xB),
* salt = APP_SALT, info = "cp-mutual|v1|<pubLo>|<pubHi>"))
* — only the two parties can compute it. When I like someone I compute the
* pair's token and store the sent like in my home log ({t:"mlike"}); when a
* received wrap carries a token in my sent set, the counterpart's identity
* emerges from MY OWN like (I know who I liked) — never from the wire.
*
* Mutual ⇒ both sides hold both payloads: the WIRE pick is the roomSecret
* from the like sent by the party with pubLo (deterministic on both sides).
* That peer-chosen value is never fed to the hub directly — both sides open
* the room with matchRoomSecret() = HKDF(roomSecret, salt=APP_SALT,
* info="cp-match-room|v1|"+token), a standard private E2E room WITHOUT
* contact exchange (§5c).
*
* Honest limits (§7): a target CAN dictionary-test received tokens against
* candidates it can enumerate (one X25519 per browsable card); the node sees
* inbox deposit timing; junk 0x12 is dropped silently under the shared
* per-poll verify budget.
*
* NOTE: tokens and roomSecrets are SECRETS — never log them, never put them
* in error messages.
*/
import { decode as cborDecode, encode as cborEncode } from "@ipld/dag-cbor";
import { x25519 } from "@noble/curves/ed25519";
import { APP_SALT, nsKey } from "../config";
import { myXIdentity } from "../core/contacts";
import type { HomeState, MLikeOp } from "../core/home-log";
import { sanitizeName } from "../core/home-log";
import { Session } from "../core/session";
import { fromB64url, randomBytes, toB64url, type Bytes } from "../lib/crypto";
import type { Wrap } from "../lib/protocol";
import { deriveXKeyPair, unwrap, wrapTo, type XKeyPair } from "../lib/wrapbox";
import { parseEnvelope, publicRoom, ENV_DOC, type PublicRoom } from "./mailbox-io";
import { isShard, sanitizeText, signDoc, verifyDoc, CARD_BLURB_MAX, type CardDoc } from "./public-doc";
import { inboxRoom, poolRoom } from "./public-rooms";
const utf8 = (s: string): Bytes => new TextEncoder().encode(s) as Bytes;
/** 0x12 | dagCbor(Wrap) — sealed dead-drop envelope (§3; no CID prefix). */
export const ENV_WRAP = 0x12;
const B64URL_43 = /^[A-Za-z0-9_-]{43}$/;
/** Wrap ct ceiling: the like payload is ~200 B; anything bigger is junk. */
const WRAP_CT_B64_MAX = 720;
/** Sealed payload plaintext ceiling (decoded). */
const WRAP_PT_MAX = 512;
/** Received-like store cap (newest win; tokens in MY sent set never evicted). */
const RECV_MAX = 500;
/** Skip-list cap. */
const SKIP_MAX = 1000;
/** Shared spam budget per pool browse (docs signature-verified per walk). */
const VERIFY_MAX_PER_BROWSE = 200;
// ---- mutual token (§2) ---------------------------------------------------------
/**
* mutualToken(A,B): HKDF over the pair's X25519 shared secret, info-bound to
* the sorted identity pubs — both sides derive it, nobody else can. NOT
* pool-scoped on purpose: a mutual pair is a match wherever the likes landed.
*/
export async function mutualToken(mySeed: string, myPub: string, peerPub: string, peerXPub: string): Promise<string> {
const myX = await deriveXKeyPair(mySeed, APP_SALT);
const peerX = fromB64url(peerXPub);
if (peerX.length !== 32) throw new Error("bad peer xPub");
const ss = x25519.getSharedSecret(myX.priv, peerX) as Bytes;
const [lo, hi] = myPub < peerPub ? [myPub, peerPub] : [peerPub, myPub];
const ikm = await crypto.subtle.importKey("raw", ss as BufferSource, "HKDF", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{
name: "HKDF",
hash: "SHA-256",
salt: utf8(APP_SALT) as BufferSource,
info: utf8(`cp-mutual|v1|${lo}|${hi}`) as BufferSource,
},
ikm,
256,
);
return toB64url(new Uint8Array(bits));
}
// ---- 0x12 wrap envelope --------------------------------------------------------
export function buildWrapEnvelope(w: Wrap): Bytes {
const body = cborEncode(w);
const out = new Uint8Array(1 + body.length);
out[0] = ENV_WRAP;
out.set(body, 1);
return out as Bytes;
}
/** Clamp-parse one 0x12 envelope; null for anything else (silent drop). */
export function parseWrapEnvelope(raw: Uint8Array): Wrap | null {
try {
if (raw.length < 2 || raw.length > 4096 || raw[0] !== ENV_WRAP) return null;
const w = cborDecode(raw.subarray(1)) as Partial<Wrap>;
if (!w || typeof w !== "object" || Array.isArray(w)) return null;
const { to, toX, ephPub, iv, ct } = w;
for (const k of [to, toX, ephPub]) {
if (typeof k !== "string" || !B64URL_43.test(k) || fromB64url(k).length !== 32) return null;
}
if (typeof iv !== "string" || iv.length === 0 || iv.length > 24) return null;
if (typeof ct !== "string" || ct.length === 0 || ct.length > WRAP_CT_B64_MAX) return null;
return { to: to!, toX: toX!, ephPub: ephPub!, iv, ct };
} catch {
return null;
}
}
// ---- like payload --------------------------------------------------------------
interface LikePayload {
v: 1;
kind: "like";
pool: string;
token: string;
roomSecret: string;
ts: number;
}
function clampLikePayload(pt: Uint8Array): LikePayload | null {
try {
if (pt.length > WRAP_PT_MAX) return null;
const p = cborDecode(pt) as Partial<LikePayload>;
if (!p || typeof p !== "object" || Array.isArray(p)) return null;
if (p.v !== 1 || p.kind !== "like") return null;
if (!isShard(p.pool)) return null;
if (typeof p.token !== "string" || !B64URL_43.test(p.token)) return null;
if (typeof p.roomSecret !== "string" || !B64URL_43.test(p.roomSecret)) return null;
if (typeof p.ts !== "number" || !Number.isSafeInteger(p.ts) || p.ts <= 0 || p.ts > Date.now() + 120_000) return null;
return { v: 1, kind: "like", pool: p.pool, token: p.token, roomSecret: p.roomSecret, ts: p.ts };
} catch {
return null;
}
}
// ---- received-like store (device-local; re-derivable by re-polling) ------------
const RECV_KEY = nsKey("match-recv");
interface RecvLike {
pool: string;
roomSecret: string;
ts: number;
}
type RecvMap = Record<string, RecvLike>; // token → payload
function loadRecv(): RecvMap {
try {
const raw = localStorage.getItem(RECV_KEY);
const m = raw ? (JSON.parse(raw) as unknown) : {};
if (!m || typeof m !== "object" || Array.isArray(m)) return {};
const out: RecvMap = {};
for (const [token, v] of Object.entries(m as Record<string, Partial<RecvLike>>)) {
if (!B64URL_43.test(token)) continue;
if (!v || typeof v.pool !== "string" || typeof v.roomSecret !== "string" || typeof v.ts !== "number") continue;
out[token] = { pool: v.pool, roomSecret: v.roomSecret, ts: v.ts };
}
return out;
} catch {
return {};
}
}
function saveRecv(map: RecvMap): void {
// Starvation defense: a token that is in MY sent set is match-relevant (it
// is, or may become, a mutual) — a flood of junk wraps must never evict it
// from the capped store. Only the anonymous remainder competes for the cap.
const sent = new Set([...(Session.selfroom?.state.mlikes.values() ?? [])].map((l) => l.token));
const keep: [string, RecvLike][] = [];
const rest: [string, RecvLike][] = [];
for (const e of Object.entries(map)) (sent.has(e[0]) ? keep : rest).push(e);
rest.sort((a, b) => b[1].ts - a[1].ts);
const entries = [...keep, ...rest].slice(0, Math.max(RECV_MAX, keep.length));
try {
localStorage.setItem(RECV_KEY, JSON.stringify(Object.fromEntries(entries)));
} catch {}
}
// ---- change feed ---------------------------------------------------------------
const listeners = new Set<() => void>();
/** Subscribe to match-state changes (new received likes / sent likes). */
export function onMatchesChanged(fn: () => void): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
function notify(): void {
for (const fn of listeners) {
try {
fn();
} catch {}
}
}
// ---- inbox ingestion (wired into the creq poll walk) ---------------------------
export interface WrapIngest {
myPub: string;
myX: XKeyPair;
/** My own inboxRoom id — the AAD roomId every wrap to me must bind. */
roomId: string;
/** Set true when at least one NEW like landed (notify after the walk). */
changed: boolean;
}
/** Per-poll ingestion context; null when no identity/mailbox. */
export async function prepareWrapIngest(): Promise<WrapIngest | null> {
const id = Session.identity;
if (!id) return null;
try {
const myPub = id.identity.publicKeyB64;
return { myPub, myX: await deriveXKeyPair(id.seed, APP_SALT), roomId: await inboxRoom(myPub), changed: false };
} catch {
return null;
}
}
/**
* Try to ingest one replayed inbox payload as a sealed like. Returns true when
* the bytes were a 0x12 envelope (whether or not it opened — callers charge
* the spam budget either way). Anything that fails to open or clamp is
* dropped silently (§3 receiver rules).
*/
export async function ingestWrapPayload(raw: Uint8Array, ctx: WrapIngest): Promise<boolean> {
const w = parseWrapEnvelope(raw);
if (!w) return false;
if (w.to !== ctx.myPub) return true; // not addressed to me — opaque, skip
const pt = await unwrap(APP_SALT, ctx.roomId, w, ctx.myX);
if (!pt) return true;
const like = clampLikePayload(pt);
if (!like) return true;
const map = loadRecv();
const prev = map[like.token];
if (!prev || like.ts > prev.ts) {
map[like.token] = { pool: like.pool, roomSecret: like.roomSecret, ts: like.ts };
saveRecv(map);
ctx.changed = true;
}
return true;
}
/** Call after a poll walk that set ctx.changed — fans out to subscribers. */
export function finishWrapIngest(ctx: WrapIngest): void {
if (ctx.changed) notify();
}
// ---- skips (local-only, never rendered again) ----------------------------------
const SKIP_KEY = nsKey("match-skip");
function loadSkips(): string[] {
try {
const list = JSON.parse(localStorage.getItem(SKIP_KEY) ?? "[]") as unknown;
return Array.isArray(list) ? list.filter((x): x is string => typeof x === "string").slice(-SKIP_MAX) : [];
} catch {
return [];
}
}
export function skipCard(pool: string, pub: string): void {
const list = loadSkips();
const key = `${pool}|${pub}`;
if (!list.includes(key)) list.push(key);
try {
localStorage.setItem(SKIP_KEY, JSON.stringify(list.slice(-SKIP_MAX)));
} catch {}
}
export function isSkipped(pool: string, pub: string): boolean {
return loadSkips().includes(`${pool}|${pub}`);
}
// ---- my card (publish / retire / re-seed) --------------------------------------
export type CardOutcome = { ok: true } | { ok: false; reason: "invalid" | "noname" | "offline" | "deposit" };
function myCardName(): string {
const state = Session.selfroom?.state;
const profileName = (state?.profileSrc?.doc as { name?: unknown } | undefined)?.name;
if (typeof profileName === "string" && sanitizeName(profileName)) return sanitizeName(profileName);
const settingsName = state?.settings.name;
return typeof settingsName === "string" ? sanitizeName(settingsName) : "";
}
async function openPoolRoom(pool: string): Promise<PublicRoom | null> {
try {
return publicRoom(await poolRoom(pool));
} catch {
return null;
}
}
/** Sign + deposit my card for `pool` and record the source in the home log. */
export async function publishCard(pool: string, blurb: string, retired = false): Promise<CardOutcome> {
const id = Session.identity;
const room = Session.selfroom;
if (!id || !room) return { ok: false, reason: "offline" };
if (!isShard(pool)) return { ok: false, reason: "invalid" };
const name = myCardName();
if (!name) return { ok: false, reason: "noname" };
const cleanBlurb = sanitizeText(blurb, CARD_BLURB_MAX);
const prev = room.state.mcards.get(pool);
const seq = (prev?.seq ?? 0) + 1;
const ts = Math.max(Date.now(), (prev?.ts ?? 0) + 1);
const x = await myXIdentity(id.identity, id.seed, name);
const doc: CardDoc = {
ts,
pool,
seq,
blurb: cleanBlurb,
name: x.name,
xPub: x.xPub,
xSig: x.xSig,
...(retired ? { retired: true as const } : {}),
};
const mbx = await openPoolRoom(pool);
if (!mbx) return { ok: false, reason: "offline" };
const signed = await signDoc(id.identity, "card", doc);
const r = await mbx.depositDoc(signed);
if (!r.ok) return { ok: false, reason: "deposit" };
// `name` records what the public doc was SIGNED over, so §6 re-seeding can
// tell a byte-identical re-deposit from a rename that needs a new revision
await room.appendHomeOp({ t: "mcard", ts, pool, seq, blurb: cleanBlurb, name: x.name, ...(retired ? { retired: true } : {}) });
notify();
return { ok: true };
}
/** Withdraw my card from a pool (LWW retired revision). */
export function retireCard(pool: string): Promise<CardOutcome> {
const src = Session.selfroom?.state.mcards.get(pool);
return publishCard(pool, src?.blurb ?? "", true);
}
/**
* §6 re-arm on app open: re-sign + re-deposit every card source (retired ones
* INCLUDED — the withdrawal must outlive the older active revision in the
* public window). Deterministic Ed25519 over identical fields keeps this
* byte-identical per (seq, ts) ⇒ server-side dedup makes it free.
*/
export async function reseedMyCards(): Promise<void> {
const id = Session.identity;
const state = Session.selfroom?.state;
if (!id || !state || state.mcards.size === 0) return;
const name = myCardName();
if (!name) return;
const x = await myXIdentity(id.identity, id.seed, name);
for (const src of [...state.mcards.values()]) {
try {
if (src.name !== x.name) {
// The profile name changed since this revision was signed (or the
// source predates name tracking): re-signing over the same (seq, ts)
// with a different name would break the byte-identical-dedup claim
// AND leave two different docs fighting over one LWW slot. Bump seq
// instead — a NEW revision that makes the rename stick everywhere.
await publishCard(src.pool, src.blurb, src.retired === true);
continue;
}
const doc: CardDoc = {
ts: src.ts,
pool: src.pool,
seq: src.seq,
blurb: sanitizeText(src.blurb, CARD_BLURB_MAX),
name: x.name,
xPub: x.xPub,
xSig: x.xSig,
...(src.retired ? { retired: true as const } : {}),
};
const mbx = await openPoolRoom(src.pool);
if (!mbx) continue; // this pool's mailbox is unreachable — try the rest
await mbx.depositDoc(await signDoc(id.identity, "card", doc));
} catch {}
}
}
// ---- pool browse ---------------------------------------------------------------
export interface PoolCard {
pub: string;
pool: string;
name: string;
blurb: string;
xPub: string;
xSig: string;
ts: number;
seq: number;
cidStr: string;
}
export interface PoolView {
reached: boolean;
/** Swipeable cards: newest first; own/retired/skipped/liked/blocked removed. */
cards: PoolCard[];
/** The verify or page budget was hit — the view may be partial. */
capped: boolean;
}
/**
* Backward-walk poolRoom(pool) and fold cards LWW per author by
* (seq, ts, cid). Verify-or-drop under the shared spam budget; render cap =
* ONE card per author per pool (the LWW slot itself).
*/
export async function browsePool(pool: string): Promise<PoolView> {
const mbx = await openPoolRoom(pool);
if (!mbx) return { reached: false, cards: [], capped: false };
const byPub = new Map<string, PoolCard & { retired: boolean }>();
let verified = 0;
const walk = await mbx.walkBackward(async (m) => {
const env = parseEnvelope(m.payload);
if (!env || env.type !== ENV_DOC) return;
if (verified >= VERIFY_MAX_PER_BROWSE) return true;
verified++;
const v = await verifyDoc(env.body, { kinds: ["card"], shard: pool, cid: env.cid });
if (!v) return;
const d = v.doc as CardDoc;
const prev = byPub.get(v.pub);
if (
!prev ||
d.seq > prev.seq ||
(d.seq === prev.seq && (d.ts > prev.ts || (d.ts === prev.ts && v.cidStr > prev.cidStr)))
) {
byPub.set(v.pub, {
pub: v.pub,
pool: d.pool,
name: d.name,
blurb: d.blurb,
xPub: d.xPub,
xSig: d.xSig,
ts: d.ts,
seq: d.seq,
cidStr: v.cidStr,
retired: d.retired === true,
});
}
});
const myPub = Session.identity?.identity.publicKeyB64;
const state = Session.selfroom?.state;
const blocked = new Set(state?.modSrc?.blocked ?? []);
const cards = [...byPub.values()]
.filter((c) => !c.retired)
.filter((c) => c.pub !== myPub)
.filter((c) => !blocked.has(c.pub))
.filter((c) => !isSkipped(pool, c.pub))
.filter((c) => !(state?.mlikes.has(`${c.pub}|${pool}`) ?? false))
.sort((a, b) => b.ts - a.ts)
.map(({ retired: _r, ...card }) => card);
return { reached: walk.reached, cards, capped: walk.stopped };
}
// ---- likes ---------------------------------------------------------------------
export type LikeOutcome = { ok: true; mutual: boolean } | { ok: false; reason: "invalid" | "offline" | "deposit" };
/**
* Like one card: seal an anonymous dead-drop into the author's inbox and
* record the sent like in my home log. Returns mutual:true when the pair's
* token is ALREADY in my received set (they liked me first).
*/
export async function likeCard(card: PoolCard): Promise<LikeOutcome> {
const id = Session.identity;
const room = Session.selfroom;
if (!id || !room) return { ok: false, reason: "offline" };
const myPub = id.identity.publicKeyB64;
if (card.pub === myPub || !isShard(card.pool)) return { ok: false, reason: "invalid" };
let token: string;
let inbox: PublicRoom | null;
try {
token = await mutualToken(id.seed, myPub, card.pub, card.xPub);
inbox = publicRoom(await inboxRoom(card.pub));
} catch {
return { ok: false, reason: "invalid" };
}
if (!inbox) return { ok: false, reason: "offline" };
const prev = room.state.mlikes.get(`${card.pub}|${card.pool}`);
const roomSecret = prev?.roomSecret ?? toB64url(randomBytes(32));
const ts = Math.max(Date.now(), (prev?.ts ?? 0) + 1);
const payload = cborEncode({
v: 1,
kind: "like",
pool: card.pool,
token,
roomSecret,
ts,
} satisfies LikePayload) as Bytes;
const wrap = await wrapTo(APP_SALT, await inboxRoom(card.pub), card.pub, card.xPub, payload);
const r = await inbox.depositRaw(buildWrapEnvelope(wrap));
if (!r.ok) return { ok: false, reason: "deposit" };
await room.appendHomeOp({
t: "mlike",
ts,
pool: card.pool,
target: card.pub,
token,
roomSecret,
...(card.name ? { name: card.name } : {}),
} satisfies MLikeOp);
notify();
return { ok: true, mutual: like$isMutual(token) };
}
function like$isMutual(token: string): boolean {
return token in loadRecv();
}
// ---- match derivation ----------------------------------------------------------
export interface Match {
/** The matched peer's Ed25519 pub. */
peer: string;
/** Display name captured from their card at like time ("" if unknown). */
name: string;
pool: string;
/**
* The WIRE room secret — pubLo's like's roomSecret (both sides agree).
* NEVER open a hub room with this directly: it is peer-chosen material.
* Feed it through matchRoomSecret() first.
*/
roomSecret: string;
/** The pair's mutualToken — the KDF context for the room key. SECRET. */
token: string;
/** Newest of the two like timestamps. */
ts: number;
}
/**
* The EFFECTIVE match-room secret (§5c): never feed the peer-chosen wire
* roomSecret to the hub — both sides derive
* effectiveSecret = b64url(HKDF(ikm = rawBytes(roomSecret),
* salt = UTF8(APP_SALT), info = "cp-match-room|v1|" + token))
* and open the room with THAT. The token is pair-private and full-entropy,
* so the derived secret is unique per pair (a replayed or attacker-chosen
* wire secret cannot collide two rooms) and carries a 256-bit entropy floor
* regardless of the wire value.
*/
export async function matchRoomSecret(m: { roomSecret: string; token: string }): Promise<string> {
const raw = fromB64url(m.roomSecret);
if (raw.length !== 32) throw new Error("bad room secret");
const ikm = await crypto.subtle.importKey("raw", raw as BufferSource, "HKDF", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{
name: "HKDF",
hash: "SHA-256",
salt: utf8(APP_SALT) as BufferSource,
info: utf8(`cp-match-room|v1|${m.token}`) as BufferSource,
},
ikm,
256,
);
return toB64url(new Uint8Array(bits));
}
/** Conversation id namespace for match chats (never collides with pubs/gids). */
export const MATCH_CONV_PREFIX = "m~";
export const matchConvId = (peer: string): string => `${MATCH_CONV_PREFIX}${peer}`;
export function matchPeerOf(convId: string): string | null {
return convId.startsWith(MATCH_CONV_PREFIX) ? convId.slice(MATCH_CONV_PREFIX.length) : null;
}
/**
* Derive the current matches: my sent-like tokens ∩ received-wrap tokens.
* Room-secret rule (§5c): pubLo's like's roomSecret — when I am pubLo it is
* MY mlike's secret, otherwise the received payload's. Deduped per peer
* (a pair mutual in two pools is still ONE pair room).
*/
export function deriveMatches(state: HomeState | null | undefined, myPub: string | null | undefined): Match[] {
if (!state || !myPub) return [];
const recv = loadRecv();
const byPeer = new Map<string, Match>();
for (const like of state.mlikes.values()) {
const got = recv[like.token];
if (!got) continue;
const iAmLo = myPub < like.target;
// Multi-device double-like race: two of MY devices liking the same target
// concurrently each mint their own roomSecret; the (target, pool) mlike
// slot converges via LWW, so the roomSecret picked here eventually agrees
// on every device — but messages already appended into the LOSER's room
// are stranded there (nobody re-derives that room), and an already-open
// ChatRoom keeps serving the stale secret until it is reopened. The chat
// service closes cached match rooms when this pick changes so the next
// open uses the winner.
const roomSecret = iAmLo ? like.roomSecret : got.roomSecret;
const m: Match = {
peer: like.target,
name: like.name ?? "",
pool: like.pool,
roomSecret,
token: like.token,
ts: Math.max(like.ts, got.ts),
};
const prev = byPeer.get(like.target);
if (!prev || m.ts > prev.ts) byPeer.set(like.target, m);
}
return [...byPeer.values()].sort((a, b) => b.ts - a.ts);
}
/** The current matches for this session (folded home log + received store). */
export function matches(): Match[] {
return deriveMatches(Session.selfroom?.state, Session.identity?.identity.publicKeyB64 ?? null);
}
export function matchByConvId(convId: string): Match | null {
const peer = matchPeerOf(convId);
if (!peer) return null;
return matches().find((m) => m.peer === peer) ?? null;
}
/**
* "N persoane te-au apreciat": received tokens with NO matching sent like —
* anonymous by construction (the payload names nobody; only a like of mine
* toward the right person would make the token meaningful).
*/
export function likedMeCount(): number {
const state = Session.selfroom?.state;
const sent = new Set([...(state?.mlikes.values() ?? [])].map((l) => l.token));
let n = 0;
for (const token of Object.keys(loadRecv())) if (!sent.has(token)) n++;
return n;
}
/** Sent likes not (yet) mutual — for the honest "trimise" counter. */
export function sentPendingCount(): number {
const state = Session.selfroom?.state;
if (!state) return 0;
const recv = loadRecv();
const seen = new Set<string>();
for (const l of state.mlikes.values()) if (!(l.token in recv)) seen.add(l.token);
return seen.size;
}
|