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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760 | /**
* Public signed-document codec (docs/PROTOCOL.md §3).
*
* Wire form:
* doc : deterministic dag-cbor map
* sigMsg = UTF8(tag + "|" + APP_SALT + "|") || dagCbor(doc)
* Signed = dagCbor({ p: <32B raw pub>, s: <64B ed25519 sig>, d: doc })
* cid = CIDv1(dag-cbor 0x71, sha2-256(Signed bytes)) — doc id + dedup key
*
* verifyDoc implements the §3 receiver rules IN ORDER: sha2-256 multihash
* only → re-hash bytes against the envelope cid (when given) → verify the
* signature with the tag of an expected kind → validate fields with clamps
* (lengths, slug shapes, ts ≤ now+2 min) → check binding (`p` == the pub the room
* derives from, `to` == the identity the room was fetched for) → return null
* on ANY failure, silently — this module never throws on wire input.
*
* The kind is NOT a doc field: each kind signs under its own domain-separated
* tag, so a signature can only ever verify under one tag. Receivers pass the
* kinds their room accepts and the matching tag identifies the kind.
*/
import { decode as cborDecode, encode as cborEncode } from "@ipld/dag-cbor";
import { CID } from "multiformats/cid";
import { sha256 } from "multiformats/hashes/sha2";
import { APP_SALT } from "../config";
import { verifyContactCert } from "../core/contacts";
import { sanitizeName } from "../core/home-log";
import { fromB64, fromB64url, toB64url, type Bytes } from "../lib/crypto";
import { verifyRaw, type Identity } from "../lib/identity";
const utf8 = (s: string): Bytes => new TextEncoder().encode(s) as Bytes;
export const DAG_CBOR_CODE = 0x71;
export const RAW_CODE = 0x55;
const SHA2_256 = 0x12;
export type DocKind =
| "profile"
| "mod"
| "post"
| "comment"
| "like"
| "creq"
| "cack"
| "activity"
| "join"
| "card";
const TAGS: Record<DocKind, string> = {
profile: "cp-profile|v1",
mod: "cp-mod|v1",
post: "cp-post|v1",
comment: "cp-comment|v1",
like: "cp-like|v1",
creq: "cp-creq|v1",
cack: "cp-cack|v1",
activity: "cp-activity|v1",
join: "cp-join|v1",
card: "cp-card|v1",
};
// ---- field caps (§3 doc-kinds table) -----------------------------------------
export const BIO_MAX = 500;
export const COMMENT_MAX = 1000;
export const CREQ_MSG_MAX = 200;
export const AVATAR_MAX_BYTES = 131_072; // 128 KiB
export const MOD_HIDDEN_MAX = 500;
export const MOD_BLOCKED_MAX = 200;
export const POST_TEXT_MAX = 2000;
export const POST_IMGS_MAX = 4;
/** Sealed profile sections per profile doc (§5b — one per group). */
export const SEALED_SECTIONS_MAX = 8;
/** Sealed-box ciphertext ceiling: 8 KiB raw (≈10.9 K b64 chars). */
export const SEALED_CT_MAX_BYTES = 8192;
const SEALED_CT_B64_MAX = 10_924;
/** Per-image display bytes ceiling (media.ts DISPLAY_HARD is 700 KiB). */
export const POST_IMG_MAX_BYTES = 786_432; // 768 KiB
export const CARD_BLURB_MAX = 300;
export const ACT_TITLE_MAX = 80;
export const ACT_DESC_MAX = 1000;
export const ACT_LOC_MAX = 120;
/** Activity window sanity ceiling: no start/end past this (year 2100). */
export const ACT_TS_MAX = 4_102_444_800_000;
const NAME_MAX = 40;
const DIM_MAX = 8192;
const TS_SKEW_MS = 120_000; // ts ≤ now + 2 min
// ---- text sanitation ---------------------------------------------------------
// NAME_STRIP (home-log) minus \n: multi-line text keeps newlines but no other
// control/bidi/zero-width character survives the wire.
// eslint-disable-next-line no-control-regex
const TEXT_STRIP = /[\u0000-\u0009\u000B-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g;
/**
* Canonical multi-line text form: strip control chars (newline survives),
* collapse 3+ blank lines, trim, clamp to `max` UTF-16 units. Receivers REJECT
* text that is not already its own sanitized form (never normalize-then-verify
* — same discipline as display names, §2b/§3).
*/
export function sanitizeText(s: string, max: number): string {
return s.replace(TEXT_STRIP, "").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim().slice(0, max).trim();
}
function isCanonText(v: unknown, max: number, minLen = 0): v is string {
return typeof v === "string" && v.length <= max && v.length >= minLen && v === sanitizeText(v, max);
}
function isCanonName(v: unknown): v is string {
return typeof v === "string" && v.length > 0 && v.length <= NAME_MAX && v === sanitizeName(v);
}
const PUB_RE = /^[A-Za-z0-9_-]{43}$/;
const SIG_RE = /^[A-Za-z0-9_-]{86}$/;
function isPub(v: unknown): v is string {
if (typeof v !== "string" || !PUB_RE.test(v)) return false;
try {
return fromB64url(v).length === 32;
} catch {
return false;
}
}
function isSig(v: unknown): v is string {
if (typeof v !== "string" || !SIG_RE.test(v)) return false;
try {
return fromB64url(v).length === 64;
} catch {
return false;
}
}
/** A wire CID string: CIDv1, sha2-256 multihash, dag-cbor or raw codec. */
function isCidStr(v: unknown): v is string {
if (typeof v !== "string" || v.length === 0 || v.length > 128) return false;
try {
const cid = CID.parse(v);
return cid.version === 1 && cid.multihash.code === SHA2_256 && (cid.code === DAG_CBOR_CODE || cid.code === RAW_CODE);
} catch {
return false;
}
}
/**
* One slug component of a shard/pool/county/category (§2): OPEN vocabulary at
* the wire, shape-validated only — lowercase ASCII letters, digits and
* hyphens, 1–24 chars. The curated lists (categories.ts / geo.ts) drive
* pickers and labels in the UI; the wire deliberately does NOT enforce
* membership, so appending new slugs is never a breaking change (a newer
* client's doc with an unknown slug still verifies here and renders as the
* raw slug). Room bindings stay strict string equality and never needed the
* enum.
*/
const SLUG_RE = /^[a-z0-9-]{1,24}$/;
export function isSlug(v: unknown): v is string {
return typeof v === "string" && SLUG_RE.test(v);
}
/**
* A feed shard string: "<category>|<countySlug>" (§2) — two shape-valid slug
* components joined by "|". Open-vocabulary like the components (see isSlug);
* the feed/pool room binding (`doc.shard`/`doc.pool` == the room's shard) is
* what pins a doc to the room it was fetched from.
*/
export function isShard(v: unknown): v is string {
if (typeof v !== "string" || v.length > 64) return false;
const bar = v.indexOf("|");
if (bar < 0) return false;
return isSlug(v.slice(0, bar)) && isSlug(v.slice(bar + 1));
}
// ---- audience-sealed shapes (§5b) ---------------------------------------------
/**
* One sealed box: AES-GCM under kGroup(g,n) = HKDF(G_n, salt=APP_SALT,
* info="cp-group-op|v1"), AAD = "cp-aud|v1|<gidHint>|<epoch>|<ownerPub>"
* (binds the ciphertext to its group, epoch AND author — a box can never be
* replayed into another owner's doc or another epoch). iv/ct are standard
* base64 of the AtRestCipher envelope's 12-byte IV and ct‖tag.
*/
export interface SealedBoxEnv {
v: 1;
iv: string;
ct: string;
}
/** A sealed profile section reference: which group/epoch key opens the box. */
export interface SealedSectionRef {
gidHint: string;
epoch: number;
box: SealedBoxEnv;
}
/** 22-char b64url decoding to exactly 16 bytes — a public gidHint. */
const HINT_RE = /^[A-Za-z0-9_-]{22}$/;
/** 16-byte b64url id — the same shape serves activity aids (P1). */
export function isAid(v: unknown): v is string {
return isHint(v);
}
function isHint(v: unknown): v is string {
if (typeof v !== "string" || !HINT_RE.test(v)) return false;
try {
return fromB64url(v).length === 16;
} catch {
return false;
}
}
function goodEpoch(v: unknown): v is number {
return typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 1_000_000;
}
/** Clamp one sealed-box envelope: v:1, 12-byte iv, ct ≤ 8 KiB (+ GCM tag). */
function clampBoxEnv(v: unknown): SealedBoxEnv | null {
if (!isPlainMap(v)) return null;
const { v: ver, iv, ct } = v as Partial<SealedBoxEnv>;
if (ver !== 1 || typeof iv !== "string" || typeof ct !== "string") return null;
if (iv.length > 24 || ct.length === 0 || ct.length > SEALED_CT_B64_MAX) return null;
try {
if (fromB64(iv).length !== 12) return null;
const raw = fromB64(ct);
if (raw.length < 16 || raw.length > SEALED_CT_MAX_BYTES + 16) return null;
} catch {
return null;
}
return { v: 1, iv, ct };
}
function goodTs(v: unknown): v is number {
return typeof v === "number" && Number.isSafeInteger(v) && v > 0 && v <= Date.now() + TS_SKEW_MS;
}
function goodSeq(v: unknown): v is number {
return typeof v === "number" && Number.isSafeInteger(v) && v > 0;
}
// ---- typed docs ---------------------------------------------------------------
export interface AvatarRef {
cid: string;
mime: "image/webp" | "image/jpeg";
w: number;
h: number;
bytes: number;
}
export interface ProfileDoc {
ts: number;
seq: number;
name: string;
bio: string;
/** Shape-validated slug (isSlug) — open vocabulary; geo.ts curates the UI list. */
county: string;
/** ≤8 unique shape-validated slugs — open vocabulary; categories.ts curates the UI list. */
categories: string[];
avatar?: AvatarRef;
xPub: string;
xSig: string;
commentPolicy: "open" | "off";
/** Audience-restricted sections, sealed under group epoch keys (§5b). */
sealed?: SealedSectionRef[];
}
export interface ModDoc {
ts: number;
seq: number;
hidden: string[]; // comment cids
blocked: string[]; // author pubs
}
export interface CommentDoc {
ts: number;
to: string;
text: string;
replyTo?: string;
}
/** One post image: thumb + display unixfs roots (0x11 blocks in the room). */
export interface PostImgRef {
thumbCid: string;
cid: string; // display root
mime: "image/webp" | "image/jpeg";
w: number;
h: number;
bytes: number; // display byte length
}
export interface PostDoc {
ts: number;
shard: string;
text: string;
imgs: PostImgRef[];
replyTo?: string;
/** Audience restriction (§5b): which group/epoch key opens `box`. */
aud?: { gidHint: string; epoch: number };
/** The sealed post body (dag-cbor {v:1, text}); present iff `aud` is. */
box?: SealedBoxEnv;
}
export interface LikeDoc {
ts: number;
re: string; // post cid
shard: string;
}
/**
* One activity (P1): LWW per (pub, aid) by (seq, ts, cid) — the organizer
* edits/cancels by republishing the SAME aid with a bumped seq. Rides the
* feed shard rooms (organizer's stripe); no new room derivations.
* Group-restricted activities keep the TITLE public (the discoverable shell)
* while desc/loc live in the sealed box: wire `desc` MUST be "" and `loc`
* MUST be absent when `aud` is present (receivers reject otherwise).
*/
export interface ActivityDoc {
ts: number;
/** 16-byte activity id, b64url (22 chars) — minted once, stable across edits. */
aid: string;
seq: number;
shard: string;
title: string;
desc: string;
/** Activity window, epoch ms; start < end enforced at the wire. */
start: number;
end: number;
loc?: string;
/** Present (and always exactly `true`) on a cancelled activity. */
cancelled?: true;
visibility: "public" | "group";
/** Audience restriction (§5b): present together with `box` iff "group". */
aud?: { gidHint: string; epoch: number };
/** Sealed dag-cbor {v:1, desc?, loc?}; present iff `aud` is. */
box?: SealedBoxEnv;
}
/**
* One join (P1): LWW per (pub, org, aid) by (ts, cid) — binds to the
* organizer's (pub, aid) pair, NOT an activity cid, so joins survive activity
* edits. Deposited into the joiner's stripe room of the SAME shard. Joins are
* PUBLIC metadata even on restricted activities (§7 — stated in-app).
*/
export interface JoinDoc {
ts: number;
/** The organizer's pub (b64url). */
org: string;
aid: string;
shard: string;
status: "going" | "out";
}
/**
* One matching card (P2): "I'm looking for a partner for <category> in
* <county>" — opt-in discoverable, deposited into poolRoom(pool). LWW per
* (pub, pool) by (seq, ts, cid); `retired: true` (only the literal) withdraws
* the card via the same LWW slot. The §3 X25519 cert (with the LITERAL name)
* rides along like creq/cack so a liker can seal a dead-drop to the author
* without any prior contact. `pool` uses the exact shard string format
* ("<category>|<county>") and is room-bound at verify time; the author
* binding deliberately does NOT apply — any identity may publish into a pool.
*/
export interface CardDoc {
ts: number;
pool: string;
seq: number;
blurb: string;
name: string;
xPub: string;
xSig: string;
/** Present (and always exactly `true`) on a withdrawn card. */
retired?: true;
}
export interface CreqDoc {
ts: number;
to: string;
name: string;
msg: string;
xPub: string;
xSig: string;
}
export interface CackDoc {
ts: number;
to: string;
name: string;
xPub: string;
xSig: string;
}
export type PublicDoc =
| ProfileDoc
| ModDoc
| PostDoc
| CommentDoc
| LikeDoc
| CreqDoc
| CackDoc
| ActivityDoc
| JoinDoc
| CardDoc;
export interface SignedDoc {
cid: CID;
bytes: Bytes;
}
export interface VerifiedDoc {
kind: DocKind;
/** Author pub (b64url of the envelope's `p`). */
pub: string;
cid: CID;
cidStr: string;
doc: PublicDoc;
}
// ---- signing ------------------------------------------------------------------
function sigMsg(kind: DocKind, docBytes: Uint8Array): Bytes {
const prefix = utf8(`${TAGS[kind]}|${APP_SALT}|`);
const out = new Uint8Array(prefix.length + docBytes.length);
out.set(prefix, 0);
out.set(docBytes, prefix.length);
return out;
}
/**
* Sign one public doc: dag-cbor the doc, sign tag|APP_SALT| ‖ docBytes with
* the Ed25519 identity, wrap as dagCbor({p,s,d}) and derive the CIDv1.
*/
export async function signDoc(identity: Identity, kind: DocKind, doc: PublicDoc): Promise<SignedDoc> {
const docBytes = cborEncode(doc);
const sig = await identity.signRaw(sigMsg(kind, docBytes));
const bytes = cborEncode({ p: fromB64url(identity.publicKeyB64), s: sig, d: doc }) as Bytes;
const digest = await sha256.digest(bytes);
return { cid: CID.create(1, DAG_CBOR_CODE, digest), bytes };
}
// ---- verification (receiver rules, in order) ----------------------------------
export interface VerifyExpect {
/** Which kinds this room accepts — the matching tag identifies the doc. */
kinds: DocKind[];
/** The pub this room derives from — `p` must equal it (binding). */
pub?: string;
/** The identity the room was fetched for — `doc.to` must equal it. */
to?: string;
/**
* The shard the feed room derives from — `doc.shard` must equal it for
* kinds that carry one (post/like). Comment docs carry no shard; they bind
* to the room only via replyTo=<postCid> of a post IN this room, which the
* caller enforces at collection time.
*/
shard?: string;
/**
* The stripe of the feed room fetched from (§2): every doc in
* feedRoom(sh, s) must be authored by a pub with stripe(pub) == s — a doc
* deposited into a foreign stripe is dropped (keeps per-stripe spam budgets
* meaningful; a legit author never writes outside their own stripe).
*/
stripe?: number;
/** The envelope's claimed cid — re-hashed against the bytes when given. */
cid?: CID;
}
function bytesEq(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
return diff === 0;
}
/** Plain data map: object, not array, not a decoded CID / bytes. */
function isPlainMap(v: unknown): v is Record<string, unknown> {
return !!v && typeof v === "object" && !Array.isArray(v) && !(v instanceof Uint8Array) && !CID.asCID(v);
}
/**
* Verify one Signed blob against this room's expectations. Returns the typed,
* clamped doc — or null on ANY failure. Never throws on wire input.
*/
export async function verifyDoc(bytes: Uint8Array, expect: VerifyExpect): Promise<VerifiedDoc | null> {
try {
// 1. sha2-256 multihash only + 2. re-hash the bytes against the cid
if (expect.cid) {
if (expect.cid.multihash.code !== SHA2_256 || expect.cid.code !== DAG_CBOR_CODE) return null;
const digest = await sha256.digest(bytes);
if (!bytesEq(digest.digest, expect.cid.multihash.digest)) return null;
}
const outer = cborDecode(bytes) as { p?: unknown; s?: unknown; d?: unknown };
if (!isPlainMap(outer)) return null;
const p = outer.p;
const s = outer.s;
if (!(p instanceof Uint8Array) || p.length !== 32) return null;
if (!(s instanceof Uint8Array) || s.length !== 64) return null;
if (!isPlainMap(outer.d)) return null;
const d = outer.d;
const pub = toB64url(p as Bytes);
const sigB64 = toB64url(s as Bytes);
// 2b. canonical-form check: the wire bytes must BE the canonical dag-cbor
// encoding of exactly {p, s, d}. dag-cbor DECODE accepts permuted map keys
// (it only rejects duplicates/non-minimal ints), so without this check a
// relayer could re-encode a valid doc with permuted keys or an extra outer
// field and mint a fresh CID for the same logical doc — breaking the CID
// as the dedup key. Re-encoding is canonical, so any such variant differs
// from `bytes` and is dropped here.
if (!bytesEq(cborEncode({ p, s, d }), bytes)) return null;
// 3. verify the signature with the tag of an expected kind. Encoding is
// deterministic and the envelope was just proven canonical, so re-encoding
// d reproduces the exact bytes the author signed over (a junk field smuggled
// INSIDE d would survive to docBytes and fail the signature instead).
const docBytes = cborEncode(d);
let kind: DocKind | null = null;
for (const k of expect.kinds) {
if (await verifyRaw(pub, sigB64, sigMsg(k, docBytes))) {
kind = k;
break;
}
}
if (kind === null) return null;
// 4. field clamps per kind (lengths, slug shapes, ts ≤ now+2 min)
const doc = await clampDoc(kind, d, pub);
if (doc === null) return null;
// 5. binding checks
if (expect.pub !== undefined && pub !== expect.pub) return null;
if (expect.to !== undefined && (doc as { to?: string }).to !== expect.to) return null;
if (expect.shard !== undefined && (kind === "post" || kind === "like" || kind === "activity" || kind === "join")) {
if ((doc as { shard?: string }).shard !== expect.shard) return null;
}
// pool binding (P2): a card fetched from poolRoom(pool) must carry that
// exact pool (author binding deliberately N/A — any identity may publish)
if (expect.shard !== undefined && kind === "card" && (doc as CardDoc).pool !== expect.shard) return null;
if (expect.stripe !== undefined && (p[0] & 0x03) !== expect.stripe) return null;
const cid = expect.cid ?? CID.create(1, DAG_CBOR_CODE, await sha256.digest(bytes));
return { kind, pub, cid, cidStr: cid.toString(), doc };
} catch {
return null; // 6. drop silently on any failure
}
}
// ---- per-kind clamps ----------------------------------------------------------
function clampAvatar(v: unknown): AvatarRef | null {
if (!isPlainMap(v)) return null;
const { cid, mime, w, h, bytes } = v as Partial<AvatarRef>;
if (!isCidStr(cid)) return null;
if (mime !== "image/webp" && mime !== "image/jpeg") return null;
const dim = (n: unknown): n is number => typeof n === "number" && Number.isSafeInteger(n) && n >= 1 && n <= DIM_MAX;
if (!dim(w) || !dim(h)) return null;
if (typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > AVATAR_MAX_BYTES) return null;
return { cid, mime, w, h, bytes };
}
function clampPostImg(v: unknown): PostImgRef | null {
if (!isPlainMap(v)) return null;
const { thumbCid, cid, mime, w, h, bytes } = v as Partial<PostImgRef>;
if (!isCidStr(thumbCid) || !isCidStr(cid)) return null;
if (mime !== "image/webp" && mime !== "image/jpeg") return null;
const dim = (n: unknown): n is number => typeof n === "number" && Number.isSafeInteger(n) && n >= 1 && n <= DIM_MAX;
if (!dim(w) || !dim(h)) return null;
if (typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > POST_IMG_MAX_BYTES) return null;
return { thumbCid, cid, mime, w, h, bytes };
}
async function clampDoc(kind: DocKind, d: Record<string, unknown>, pub: string): Promise<PublicDoc | null> {
if (!goodTs(d.ts)) return null;
const ts = d.ts;
switch (kind) {
case "profile": {
if (!goodSeq(d.seq) || !isCanonName(d.name) || !isCanonText(d.bio, BIO_MAX)) return null;
// county/categories are shape-validated (open vocabulary, isSlug) — a
// doc from a NEWER client that knows more slugs must not be rejected
// wholesale; the cap of 8 categories per profile is the real clamp.
if (!isSlug(d.county)) return null;
if (!Array.isArray(d.categories) || d.categories.length > 8) return null;
if (!d.categories.every(isSlug)) return null;
if (new Set(d.categories).size !== d.categories.length) return null;
if (d.commentPolicy !== "open" && d.commentPolicy !== "off") return null;
if (!isPub(d.xPub) || !isSig(d.xSig)) return null;
// §3 cert: the Ed25519 identity signed "cp-x25519|v1|…|name" — the name
// in the cert is the profile's LITERAL name (already canon-checked).
if (!(await verifyContactCert(pub, d.xPub, d.xSig, d.name))) return null;
let avatar: AvatarRef | undefined;
if (d.avatar !== undefined) {
const a = clampAvatar(d.avatar);
if (a === null) return null;
avatar = a;
}
// §5b sealed sections: ≤8, one per gidHint, each a clamped envelope.
// Existence stays public by design; only the content is opaque.
let sealed: SealedSectionRef[] | undefined;
if (d.sealed !== undefined) {
if (!Array.isArray(d.sealed) || d.sealed.length === 0 || d.sealed.length > SEALED_SECTIONS_MAX) return null;
const seen = new Set<string>();
sealed = [];
for (const raw of d.sealed) {
if (!isPlainMap(raw)) return null;
const { gidHint, epoch, box } = raw as Partial<SealedSectionRef>;
if (!isHint(gidHint) || !goodEpoch(epoch)) return null;
const env = clampBoxEnv(box);
if (env === null || seen.has(gidHint)) return null;
seen.add(gidHint);
sealed.push({ gidHint, epoch, box: env });
}
}
return {
ts,
seq: d.seq,
name: d.name,
bio: d.bio,
county: d.county,
categories: d.categories,
...(avatar ? { avatar } : {}),
xPub: d.xPub,
xSig: d.xSig,
commentPolicy: d.commentPolicy,
...(sealed ? { sealed } : {}),
};
}
case "mod": {
if (!goodSeq(d.seq)) return null;
if (!Array.isArray(d.hidden) || d.hidden.length > MOD_HIDDEN_MAX || !d.hidden.every(isCidStr)) return null;
if (!Array.isArray(d.blocked) || d.blocked.length > MOD_BLOCKED_MAX || !d.blocked.every(isPub)) return null;
return { ts, seq: d.seq, hidden: d.hidden, blocked: d.blocked };
}
case "post": {
if (!isShard(d.shard)) return null;
if (!isCanonText(d.text, POST_TEXT_MAX)) return null;
if (!Array.isArray(d.imgs) || d.imgs.length > POST_IMGS_MAX) return null;
const imgs: PostImgRef[] = [];
for (const raw of d.imgs) {
const img = clampPostImg(raw);
if (img === null) return null;
imgs.push(img);
}
if (d.replyTo !== undefined && !isCidStr(d.replyTo)) return null;
// §5b audience restriction: aud + box come together or not at all.
// Restricted posts are TEXT-ONLY in v1 (public text empty, imgs empty;
// the body lives solely inside the sealed box) — image blocks stay
// public-plane, so sealing them under group keys is out of scope here.
let aud: { gidHint: string; epoch: number } | undefined;
let box: SealedBoxEnv | undefined;
if (d.aud !== undefined || d.box !== undefined) {
if (!isPlainMap(d.aud)) return null;
const { gidHint, epoch } = d.aud as Partial<{ gidHint: string; epoch: number }>;
if (!isHint(gidHint) || !goodEpoch(epoch)) return null;
const env = clampBoxEnv(d.box);
if (env === null) return null;
if (imgs.length > 0 || d.text !== "") return null;
aud = { gidHint, epoch };
box = env;
}
if (d.text.length === 0 && imgs.length === 0 && aud === undefined) return null; // an empty post says nothing
return {
ts,
shard: d.shard,
text: d.text,
imgs,
...(d.replyTo !== undefined ? { replyTo: d.replyTo as string } : {}),
...(aud && box ? { aud, box } : {}),
};
}
case "like": {
if (!isCidStr(d.re) || !isShard(d.shard)) return null;
return { ts, re: d.re, shard: d.shard };
}
case "comment": {
if (!isPub(d.to) || !isCanonText(d.text, COMMENT_MAX, 1)) return null;
if (d.replyTo !== undefined && !isCidStr(d.replyTo)) return null;
return { ts, to: d.to, text: d.text, ...(d.replyTo !== undefined ? { replyTo: d.replyTo as string } : {}) };
}
case "activity": {
if (!isAid(d.aid) || !goodSeq(d.seq) || !isShard(d.shard)) return null;
if (!isCanonText(d.title, ACT_TITLE_MAX, 1)) return null;
if (!isCanonText(d.desc, ACT_DESC_MAX)) return null;
const goodMs = (v: unknown): v is number =>
typeof v === "number" && Number.isSafeInteger(v) && v > 0 && v <= ACT_TS_MAX;
if (!goodMs(d.start) || !goodMs(d.end) || d.start >= d.end) return null;
if (d.loc !== undefined && !isCanonText(d.loc, ACT_LOC_MAX, 1)) return null;
if (d.cancelled !== undefined && d.cancelled !== true) return null;
if (d.visibility !== "public" && d.visibility !== "group") return null;
// §5b: group visibility ⟺ aud + box present; the sealed body carries
// desc/loc — the PUBLIC desc must be empty and loc absent (title is the
// deliberately-public discoverable shell).
let aud: { gidHint: string; epoch: number } | undefined;
let box: SealedBoxEnv | undefined;
if (d.visibility === "group") {
if (!isPlainMap(d.aud)) return null;
const { gidHint, epoch } = d.aud as Partial<{ gidHint: string; epoch: number }>;
if (!isHint(gidHint) || !goodEpoch(epoch)) return null;
const env = clampBoxEnv(d.box);
if (env === null) return null;
if (d.desc !== "" || d.loc !== undefined) return null;
aud = { gidHint, epoch };
box = env;
} else if (d.aud !== undefined || d.box !== undefined) {
return null;
}
return {
ts,
aid: d.aid,
seq: d.seq,
shard: d.shard,
title: d.title,
desc: d.desc,
start: d.start,
end: d.end,
...(d.loc !== undefined ? { loc: d.loc as string } : {}),
...(d.cancelled === true ? { cancelled: true as const } : {}),
visibility: d.visibility,
...(aud && box ? { aud, box } : {}),
};
}
case "join": {
if (!isPub(d.org) || !isAid(d.aid) || !isShard(d.shard)) return null;
if (d.status !== "going" && d.status !== "out") return null;
return { ts, org: d.org, aid: d.aid, shard: d.shard, status: d.status };
}
case "card": {
if (!isShard(d.pool) || !goodSeq(d.seq)) return null;
if (!isCanonText(d.blurb, CARD_BLURB_MAX)) return null;
if (!isCanonName(d.name)) return null;
if (d.retired !== undefined && d.retired !== true) return null;
if (!isPub(d.xPub) || !isSig(d.xSig)) return null;
if (!(await verifyContactCert(pub, d.xPub, d.xSig, d.name))) return null;
return {
ts,
pool: d.pool,
seq: d.seq,
blurb: d.blurb,
name: d.name,
xPub: d.xPub,
xSig: d.xSig,
...(d.retired === true ? { retired: true as const } : {}),
};
}
case "creq": {
if (!isPub(d.to) || !isCanonName(d.name) || !isCanonText(d.msg, CREQ_MSG_MAX)) return null;
if (!isPub(d.xPub) || !isSig(d.xSig)) return null;
if (!(await verifyContactCert(pub, d.xPub, d.xSig, d.name))) return null;
return { ts, to: d.to, name: d.name, msg: d.msg, xPub: d.xPub, xSig: d.xSig };
}
case "cack": {
if (!isPub(d.to) || !isCanonName(d.name)) return null;
if (!isPub(d.xPub) || !isSig(d.xSig)) return null;
if (!(await verifyContactCert(pub, d.xPub, d.xSig, d.name))) return null;
return { ts, to: d.to, name: d.name, xPub: d.xPub, xSig: d.xSig };
}
}
}
|