@uuaid/pillar 2.8.1 → 2.8.3

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.
package/README.md CHANGED
@@ -441,6 +441,13 @@ exchange needed. For peers outside any directory, pass their key once with
441
441
  `pillar-ask <uuaid> "..." --to-pubkey HEX`. Point it at your own directory.json
442
442
  to build a private mesh.
443
443
 
444
+ An app that reads the directory itself can apply the same rule (2.8.2):
445
+ `import { directoryCarriers } from "@uuaid/pillar/discovery"`.
446
+ `directoryCarriers(doc)` returns `{ carriers, skippedRelayed }`: the bootstrap
447
+ carrier (never a relayed seed URL), then each seed URL in directory order. A
448
+ relayed seed is taken only when its entry names its relay and its URL is
449
+ `<relay>/e/<id>`, and at most `MAX_RELAYED_FROM_DIRECTORY` (4) are taken.
450
+
444
451
  ### The contacts file (`fleet.json`)
445
452
 
446
453
  ```json
@@ -528,10 +535,13 @@ and eviction do not currently prefer contacts or trusted senders.
528
535
  ### Group admin from code: `@uuaid/pillar/groups-v2`
529
536
 
530
537
  From 2.6.0 the signed pillar-group/2 admin API is a package export, so an app
531
- needs neither `pillar group` nor a deep import. It exports exactly these 11
538
+ needs neither `pillar group` nor a deep import. It exports exactly these 18
532
539
  names: `adminCreate`, `adminChange`, `adminManifestSends`, `parseMemberRef`,
533
540
  `adminOf`, `activeAdmins`, `isGroupIdV2`, `ACTIONS`, `MAX_MEMBERS`, `MAX_NAME`
534
- and `MAX_PURPOSE`.
541
+ and `MAX_PURPOSE`; and, read-only, for co-admins (`ext.admins`): `coAdminsOf`,
542
+ `adminsFault`, `parseRenameField`, `ADMINS_V`, `CO_ADMIN_POWERS`,
543
+ `MAX_CO_ADMINS` and `REFUSE_REASONS`. `adminCreate` and `adminChange` refuse to
544
+ sign a malformed `ext.admins` (error code `group-v2-admins-refused`).
535
545
 
536
546
  **No store and no receiver is exported** (one group store per home, design
537
547
  D5): there is no `RosterStore`, `MemoryRosterStore`, `GroupReceiver` or
@@ -1521,3 +1531,249 @@ its own.
1521
1531
  ## License
1522
1532
 
1523
1533
  Apache-2.0.
1534
+
1535
+ ## Spaces API (2.8.2)
1536
+
1537
+ The Spaces API (first cut as the 2.7.0-spaces.0 source candidate) adds application-owned manifest extensions and outbound
1538
+ permission gates. It does not join a Space, approve an agent, or grant authority
1539
+ from a remote charter. The host still owns those decisions.
1540
+
1541
+ `adminCreate({ ...existing, ext })` signs a detached, bounded plain JSON extension
1542
+ through the existing genesis verification and single-store path. Omitting `ext`
1543
+ keeps the ordinary empty extension. No store or receiver constructor is added to
1544
+ the public export map.
1545
+
1546
+ `pillar.syncGroupV2({ manifestPayload, permit, signal })` calls `manifestPayload`
1547
+ for **each queued manifest attempt**, including retries after a restart. The
1548
+ callback receives deeply frozen `{ groupId, recipient, op, manifest, chain,
1549
+ head: { version, hash } }`, all from the verified held record. Return a plain JSON
1550
+ object of extra payload fields, for example `{ _commons: heldCharter }`; the
1551
+ callback must verify its own charter/hash/key/head association. A throw or invalid
1552
+ return leaves the row queued and sends nothing. Extras are limited to 32 KiB of
1553
+ canonical UTF-8 JSON and 32 levels of nesting, plus existing envelope/carrier
1554
+ limits. `_group`, `text`, `thread`, `quote`, `blobRef`, `inReplyTo`, `type`, `upTo`
1555
+ and prototype-manipulation keys are forbidden. Missing `manifestPayload` keeps
1556
+ the ordinary group payload.
1557
+
1558
+ A queued row keeps one envelope (2.8.2), with or without `trustedCarriers`. Its
1559
+ id is saved on the row before the first send, by a claim: when two sync passes
1560
+ run at once, only one seals an attempt for a row. One pass owns a row from its
1561
+ first read to its last write, across every await: another pass in the same
1562
+ process skips it, and a pass records a result only while the row is still
1563
+ queued under its own attempt (2.8.2 r4). A retry runs every check
1564
+ again, including `manifestPayload` (a throw still keeps the row queued and sends
1565
+ nothing), then sends the stored envelope again: its extras are the first
1566
+ attempt's. An attempt that was delivered or acked, also during the retry, makes
1567
+ the row `sent`. A new envelope is sealed only when the route moved, when the
1568
+ stored outbox row was erased, or when the stored envelope is over 23 hours old
1569
+ (a carrier refuses an envelope over 24 hours old). Each such attempt is replaced
1570
+ once, after every check and gate, with a new group tag and new extras. The
1571
+ replaced outbox row, and the pending row of a dropped queue row, become
1572
+ `superseded`.
1573
+
1574
+ `new Pillar({ ...existing, outboundPolicy })` installs an instance-bound policy.
1575
+ `send`, `sendDirect`, `sendGroupV2` and `syncGroupV2` additionally accept `permit`
1576
+ and `signal`. Both callbacks must return exactly `true`; they may return a
1577
+ promise. Their frozen routing DTO contains only `{ phase, route, recipient,
1578
+ groupId, op, carrier? }`: phase is `seal` or `dispatch`, and route is `auto`,
1579
+ `direct`, `carrier` or `group`. A host's instance baseline should synchronously
1580
+ read current identity/admission/retirement state. An asynchronous per-call
1581
+ consent callback must recheck its captured operation after awaiting consent;
1582
+ abort the supplied lifecycle signal on revoke, close, restore or identity
1583
+ replacement. The SDK checks the signal after policy awaits and again immediately
1584
+ before sealing, direct `stream.send` (after the dial), and each parallel carrier
1585
+ fetch. It also rechecks the instance baseline after the per-call callback.
1586
+
1587
+ Refusal, callback exception or cancellation yields the stable error code
1588
+ `send-permit-denied` with a sanitized message. Group fanout stops future members,
1589
+ keeps preceding results, and returns `stopped: true`. Queued manifest attempts
1590
+ are terminally dropped on denial, including remaining attempts in that sync;
1591
+ ordinary network errors remain queued. The code is reserved for this SDK's own
1592
+ denials: a carrier refusal whose reason names it is reported as an ordinary
1593
+ `carrier-bad-response` failure (its text kept in the per-carrier `error`), and no
1594
+ other error that merely carries the code stops a fanout or drops queued sends.
1595
+ Already-attempted network operations
1596
+ cannot be recalled. Partial carrier acceptance/attempt metadata is retained in
1597
+ `error.partial` and group result `partial`; acceptance does not prove receipt by
1598
+ a recipient. No generic pending-outbox resender is introduced. Blob reservation
1599
+ and upload APIs retain their existing separate host authorization requirements;
1600
+ these gates cover the listed send transports, not a general-purpose sandbox.
1601
+
1602
+ After a public admin write, `pillar.reloadGroupV2(groupId)` verifies the stored
1603
+ record, invalidates only that existing receiver's cache, and returns its current
1604
+ state. It does not construct another receiver or expose private caches.
1605
+
1606
+ ## Trusted carriers (2.8.2, opt-in)
1607
+
1608
+ `new Pillar({ ...existing, trustedCarriers: ["https://pillar.uuaid.org", ...] })`
1609
+ names the carriers this agent trusts, by exact base URL (a trailing slash is
1610
+ ignored). Unset (`null`, the default), carrier trust is as in 2.8.1: v1 inbox
1611
+ auth to every direct carrier, and any acceptance counts. Two 2.8.2 changes apply
1612
+ either way: `syncGroupV2` sends one envelope per queued row (above), and a
1613
+ carrier acceptance before a send permit denial marks the row `delivered`. `[]` is set,
1614
+ with no carrier trusted. Any other value but an array of URL strings is a
1615
+ `TypeError`. `CarrierClient` takes the same option.
1616
+
1617
+ When it is set:
1618
+
1619
+ - Inbox auth v1 goes only to a trusted carrier that is not a relayed seed URL.
1620
+ Every other carrier, direct or relayed, gets inbox auth v2 (bound to that
1621
+ carrier's URL, used once). v1 names no carrier and stays valid for 5 minutes,
1622
+ so any carrier that receives it can replay it elsewhere. A carrier that
1623
+ refuses v2 is not read; v1 is never sent to it instead. Retired-key imports
1624
+ follow the same rule.
1625
+ - Only a trusted carrier's acceptance marks the outbox row `delivered`. When only
1626
+ other carriers (for example a relayed seed) accept, `send()` returns
1627
+ `confirmed: false` and the row stays `pending`; a trusted acceptance returns
1628
+ `confirmed: true`. `sendGroupV2` marks such a member result `confirmed: false`,
1629
+ and `syncGroupV2` keeps the queued send queued (reason `no trusted carrier
1630
+ accepted`) so a later sync sends the same envelope again.
1631
+ - A plain `send()` with `confirmed: false` is not sent again by the SDK. The app
1632
+ owns that retry: `pillar.resendOutbound(envelopeId, { recipientPublicKey,
1633
+ permit, signal })` sends the stored envelope again, byte for byte, through
1634
+ every `send()` gate and the continuity route, and returns `send()`'s result
1635
+ (a trusted acceptance marks the row `delivered`). It works the same without
1636
+ `trustedCarriers`. It sends nothing and returns `{ resent: false, reason }`
1637
+ when the row is `completed` (delivered or acked), `erased`, `superseded`,
1638
+ `rerouted` (the route no longer lands on its recipient), `expired` (over 23
1639
+ hours old; a carrier refuses an envelope over 24 hours old), `missing`, or a
1640
+ `group` row. `expired` is named before any key lookup, so it needs no
1641
+ `recipientPublicKey`. The row is read again after every dispatch gate, right
1642
+ before the bytes leave on each route: a row erased, completed or superseded
1643
+ while a permit was pending sends nothing more and returns that reason (an
1644
+ earlier carrier acceptance is still recorded, as for a denial). `syncGroupV2` retries only its own queued rows. Nothing in the SDK
1645
+ retries a `sendGroupV2` member result with `confirmed: false`, and this method
1646
+ refuses it too: a plain `send()` would carry no group context to the permit.
1647
+ On `rerouted` or `expired` the app decides whether to send anew.
1648
+
1649
+ ## Seed routes (2.8.3, opt-in)
1650
+
1651
+ `seedRoutes` gives an app a second, bounded list of carriers: seeds from a
1652
+ directory, kept apart from the fleet. A send uses a seed only when the caller
1653
+ asks for it, and only for a recipient whose verified listing names that seed.
1654
+ Callers that pass neither option keep 2.8.2 behavior.
1655
+
1656
+ ```js
1657
+ import { Pillar } from "@uuaid/pillar";
1658
+
1659
+ const pillar = new Pillar({
1660
+ keychain, mailboxPath,
1661
+ carriers: ["https://pillar.uuaid.org"], // the fleet: trust, adverts, ordinary sends
1662
+ trustedCarriers: ["https://pillar.uuaid.org"],
1663
+ registryUrl: "https://registry.uuaid.org", // where listings are verified
1664
+ seedRoutes: {
1665
+ direct: ["https://seed.example.org"], // HTTPS origins, at most 8
1666
+ relayed: ["https://relay.example.org/e/02d449a3-1fbb-267c-8f35-2e9968a79e3e"], // exact <relay>/e/<id>, at most 4
1667
+ },
1668
+ });
1669
+
1670
+ const r = await pillar.send({ recipient, recipientPublicKey, payload: { text: "hi" }, route: "listed" });
1671
+ // r.route = { seeds: ["https://seed.example.org"], accepted: [...], reason: null }
1672
+ // r.confirmed is true only when the fleet accepted. A seed's 202 alone gives via "seed", confirmed false.
1673
+
1674
+ pillar.startSeedPolling(); // apart from startCarrierPolling; stop with stopSeedPolling()
1675
+ ```
1676
+
1677
+ What the options do:
1678
+
1679
+ | Option | Values | Effect |
1680
+ | --- | --- | --- |
1681
+ | `seedRoutes` | `null` (default) or `{ direct?, relayed?, timeoutMs?, pollIntervalMs? }` | Seeds for `route` and seed polling. Set at construction; replace it with `setSeedRoutes(value)`. |
1682
+ | `setSeedRoutes(value)` | the same shape, or `null` | Replaces the seed set while the process runs (see "Changing the routes"). |
1683
+ | `send({ route })` | `null`, `"fleet"` (default) | The fleet only, as in 2.8.2. No registry read, no seed traffic. |
1684
+ | | `"listed"` | The fleet, plus each configured seed that the recipient's verified listing names. |
1685
+ | | `{ seed: url }` | The fleet, plus that one seed, on the same condition. |
1686
+ | `sendGroup` / `sendGroupV2({ route })` | as above | Passed to every member's `send()`. |
1687
+
1688
+ The rules (RedTeam Mac B directory review, items 1-4):
1689
+
1690
+ - **Caps.** Each entry is validated and canonicalized first. A direct seed is
1691
+ an HTTPS origin. A relayed seed is an exact `<relay origin>/e/<id>` URL. User
1692
+ information, a query, a fragment, a private or loopback host, and a path on a
1693
+ direct seed are refused. Duplicates of the fleet or of another entry are
1694
+ removed before the caps: 8 direct and 4 relayed. The rest are listed in
1695
+ `pillar.seedRoutes.skipped` as `{ url, reason }` (`duplicate`, `cap`, or the
1696
+ validation reason).
1697
+ - **Public connections only.** Every seed request resolves the host, refuses
1698
+ the request when any address is not global (`seed-address-refused`), and
1699
+ connects only to the checked addresses. It follows no redirect, reads at most
1700
+ 8 MiB, and stops after `timeoutMs` (default 5000 ms, at most 30000). A send
1701
+ with `route` can wait up to `timeoutMs` for the listing and up to `timeoutMs`
1702
+ for its seeds, which run beside the fleet post; a send without `route` waits
1703
+ for neither.
1704
+ All seed requests in the process share 4 slots, with 1 per origin, across
1705
+ every Pillar (owner and agents).
1706
+ - **Verified listed seed only.** For `route`, the SDK resolves the final
1707
+ recipient (after continuity and W-4) through `registryUrl` with the
1708
+ signature-checking resolver. The listing must be for that recipient and its
1709
+ sealing key. A seed gets the envelope only when the listing names it and it
1710
+ is configured. Otherwise `route.seeds` is empty and `route.reason` says why
1711
+ (`no-seed-routes`, `no-registry`, `no-fleet`, `not-listed`, `seed-not-listed`,
1712
+ `listing-not-recipient`, `listing-key-mismatch`, `listing-dead`,
1713
+ `listing-unverified:<resolver reason>`); the send continues on the fleet.
1714
+ - **A seed's 202 is storage, not delivery.** Seeds are never trusted carriers
1715
+ and never join `carriers`. Only the fleet's acceptance marks the row
1716
+ `delivered` (with `trustedCarriers` set, a trusted fleet carrier's). When
1717
+ every fleet carrier refuses and a seed accepts, `send()` returns
1718
+ `via: "seed"`, `confirmed: false`, and `carrierError`; the row stays `pending`.
1719
+ When the seeds refuse too, the fleet's error is thrown, with `route` on it.
1720
+ - **Permits stay on.** The send permit sees each seed dispatch (`carrier` is
1721
+ the seed URL). A refusal denies the send as on any carrier; a fleet
1722
+ acceptance before it is still recorded.
1723
+ - **Trust and adverts stay on the build lists.** `carriers`, `trustedCarriers`,
1724
+ carrier polling, `drainCarrierInbox`, auto-acks, read receipts, retired-key
1725
+ imports, `syncGroupV2` and `resendOutbound` do not use seeds.
1726
+ - **Group copies.** With `route`, a member copy that only a seed took is
1727
+ `confirmed: false`, and `sendGroupV2` returns `unconfirmed` (the count).
1728
+ Nothing in the SDK sends it again. A verified ack or read receipt from that
1729
+ member advances its row (`recipient_ack_at`), as for any send.
1730
+ - **Seed polling.** `startSeedPolling({ intervalMs, onError })` runs apart from the
1731
+ fleet poller. Each round sleeps a jittered 0.5x to 1.5x `intervalMs` (default
1732
+ `seedRoutes.pollIntervalMs`, 120000 ms; at least 10000 ms), then takes one
1733
+ `wait=0` page (at most 200 envelopes) from each seed in turn, with inbox auth
1734
+ v2. Each seed keeps its own cursor. A slow or empty seed costs at most
1735
+ `timeoutMs` and never delays a send or the fleet poller. `stop()` stops it
1736
+ too. `onError(error, { seed })` is called for a failed poll; if it throws,
1737
+ the error is counted (`seed.poll.onerror-threw`) and polling goes on. If the
1738
+ loop ever ends without `stopSeedPolling()`, its handle is cleared, so the
1739
+ next `startSeedPolling()` starts a new one.
1740
+ - **`pollSeedsOnce()`** runs one round now. It returns how many **new inbox
1741
+ rows** the round stored, quarantined rows included. Duplicates, items for
1742
+ another recipient, and items that fail to open are not counted. It is not a
1743
+ count of new mail to show a user.
1744
+
1745
+ ### Changing the routes: `setSeedRoutes(value)`
1746
+
1747
+ An app's route cache expires and refreshes while the process runs. Call
1748
+ `pillar.setSeedRoutes(value)` with the new set, or `null` to turn seed routes
1749
+ off. Call it on every Pillar that uses seeds (owner and agents).
1750
+
1751
+ - `value` is checked like the constructor's `seedRoutes`, against the same
1752
+ fleet. A bad value throws a `TypeError` and changes nothing. It returns the
1753
+ new normalized routes (`null` when off).
1754
+ - The next send and the next poll round use the new set. A seed that is no
1755
+ longer in it gets no new request. That includes a request still waiting on
1756
+ a send permit: the seed fetch refuses it (`seed-route-removed`), and the
1757
+ send's result comes from the fleet as usual. One already queued may still go
1758
+ within timeoutMs: a request that passed that check and waits in the seed
1759
+ concurrency limits is not called back.
1760
+ - Seeds that stay keep their cursors. The cursors of removed seeds are
1761
+ dropped, and a page that was in flight when its seed was removed writes
1762
+ nothing back. Fleet cursors are never touched.
1763
+ - `null`, or a set with no seeds, stops seed traffic. A running seed poller
1764
+ keeps running and polls nothing until a later call adds seeds. Its interval
1765
+ is the one it started with.
1766
+ - The new value replaces everything, including `timeoutMs`,
1767
+ `pollIntervalMs` and the test hooks below. Pass the whole object each time.
1768
+
1769
+ **Build `seedRoutes` field by field.** `allowPrivateUrls`, `lookup` and
1770
+ `fetch` are test hooks. `allowPrivateUrls: true` turns off the https and
1771
+ private-address checks for every seed send and poll, and it can be written in
1772
+ plain JSON. Never pass an object parsed from directory data or any other JSON
1773
+ to `new Pillar({ seedRoutes })` or `setSeedRoutes()`, and never spread one into
1774
+ it. Build `{ direct: [...], relayed: [...] }` from the checked URL strings
1775
+ only.
1776
+
1777
+ `@uuaid/pillar/seed-routes` exports the caps, `normalizeSeedRoutes`,
1778
+ `canonicalSeed`, `makeSeedFetch` and `listedSeeds` for an app that checks a
1779
+ directory itself.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.8.1",
3
+ "version": "2.8.3",
4
4
  "description": "Pillar (Protocol for Inter-agent Linked Ledger And Relay) — the secure delivery layer of UACP, the Universal Agent Communication Protocol. UACP = UUAID (identity) + Envelope (signed, encrypted container) + Pillar (relay, mailbox, routing, store-and-forward). Reference implementation of the UACP delivery layer; includes VDA-1 (IAASO-3901, in ballot) delivery attestation and a blind escrow for the Zilligon ZGN / EVM rails.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -28,6 +28,8 @@
28
28
  "./carrier-client": "./src/net/carrier-client.mjs",
29
29
  "./seed-tier": "./src/net/seed-tier.mjs",
30
30
  "./seed-registry": "./src/net/seed-registry.mjs",
31
+ "./discovery": "./src/net/discovery.mjs",
32
+ "./seed-routes": "./src/net/seed-routes.mjs",
31
33
  "./blob": "./src/blob/blob.mjs",
32
34
  "./blob/http": "./src/blob/http.mjs",
33
35
  "./blob/store": "./src/blob/store.mjs",
@@ -13,4 +13,7 @@ export {
13
13
  adminCreate, adminChange, adminManifestSends, parseMemberRef,
14
14
  adminOf, activeAdmins, isGroupIdV2,
15
15
  ACTIONS, MAX_MEMBERS, MAX_NAME, MAX_PURPOSE,
16
+ // Family A (WIRE-family-A-v1): read-side only. The builder refusal runs inside adminCreate/adminChange.
17
+ coAdminsOf, adminsFault, parseRenameField,
18
+ ADMINS_V, CO_ADMIN_POWERS, MAX_CO_ADMINS, REFUSE_REASONS,
16
19
  } from "./groups-v2.mjs";
package/src/groups-v2.mjs CHANGED
@@ -50,6 +50,18 @@ export const BUFFER_LIMITS = Object.freeze({ invites: 64, invitesPerSender: 4, b
50
50
  export const ACTIONS = Object.freeze(["create", "invite", "accept", "leave", "remove", "rename", "ext_update", "admin_transfer"]);
51
51
  export const V2_OPS = Object.freeze([
52
52
  "message", "manifest", "accept.request", "leave.request", "rename.request", "manifest.request", "equivocation",
53
+ // Family A (co-admins in groups the owner's Mac creates; WIRE-family-A-v1 §3): a co-admin asks the
54
+ // creator to invite; the creator refuses a request it will not sign. Only new apps send them.
55
+ "invite.request", "request.refused",
56
+ ]);
57
+ // Family A `ext.admins` (WIRE-family-A-v1 §2). The creator alone signs it; co-admins stay role "member".
58
+ export const ADMINS_V = "pillar-group-admins/1";
59
+ export const CO_ADMIN_POWERS = Object.freeze(["invite", "rename"]);
60
+ export const MAX_CO_ADMINS = 8;
61
+ /** `request.refused` reasons, a closed list (§3). */
62
+ export const REFUSE_REASONS = Object.freeze([
63
+ "not-co-admin", "no-power", "owner-declined", "reinvite-creator-only", "target-not-invitable",
64
+ "bad-request", "group-full", "limit", "expired", "superseded",
53
65
  ]);
54
66
 
55
67
  const ID_RE = /^grp-[0-9a-f]{32}$/;
@@ -108,6 +120,43 @@ export function signingPreimage(m) { return canonicalJson(without(m, "sig")); }
108
120
  /** Manifest hash: the full signed manifest. `prev` and `mv.hash` use it. */
109
121
  export function manifestHash(m) { return sha256Hex(canonicalJson(m)); }
110
122
 
123
+ /** A bounded plain JSON record, detached from caller mutation; internal consumer helper. */
124
+ export function boundedJsonRecord(value, maxBytes = 32768) {
125
+ let budget = maxBytes;
126
+ const seen = new Set();
127
+ const visit = (v, depth) => {
128
+ if (depth > 32 || --budget < 0) throw new Error("JSON record exceeds bounds");
129
+ if (v === null || typeof v === "boolean") return v;
130
+ if (typeof v === "string") {
131
+ budget -= Buffer.byteLength(v);
132
+ if (budget < 0) throw new Error("JSON record exceeds bounds");
133
+ return v;
134
+ }
135
+ if (typeof v === "number" && Number.isFinite(v)) return v;
136
+ if (typeof v !== "object" || (!Array.isArray(v) && (!plain(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v)))) || seen.has(v)) throw new Error("expected plain JSON record");
137
+ if (Array.isArray(v) && v.length > maxBytes) throw new Error("JSON record exceeds bounds");
138
+ if (Object.getOwnPropertySymbols(v).length) throw new Error("expected plain JSON record");
139
+ if (Array.isArray(v) && (Object.keys(v).length !== v.length || !Array.from({ length: v.length }, (_, i) => Object.hasOwn(v, i)).every(Boolean))) throw new Error("expected dense JSON array");
140
+ seen.add(v);
141
+ const out = Array.isArray(v) ? [] : {};
142
+ for (const key of Object.keys(v)) {
143
+ if (["__proto__", "prototype", "constructor"].includes(key)) throw new Error("reserved JSON key");
144
+ const d = Object.getOwnPropertyDescriptor(v, key);
145
+ if (!d || !Object.hasOwn(d, "value")) throw new Error("JSON accessors are not supported");
146
+ budget -= Buffer.byteLength(key);
147
+ if (budget < 0) throw new Error("JSON record exceeds bounds");
148
+ out[key] = visit(d.value, depth + 1);
149
+ }
150
+ if (Array.isArray(v) && (out.length !== v.length || Object.keys(v).length !== v.length)) throw new Error("expected dense JSON array");
151
+ seen.delete(v);
152
+ return out;
153
+ };
154
+ if (!plain(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new Error("expected plain JSON record");
155
+ const out = visit(value, 0);
156
+ if (Buffer.byteLength(canonicalJson(out)) > maxBytes) throw new Error("JSON record exceeds bounds");
157
+ return out;
158
+ }
159
+
111
160
  // ───────────────────────────────────────────── strict Ed25519 (RFC 8032) ──
112
161
  const L = 2n ** 252n + 27742317777372353535851937790883648493n;
113
162
  const leInt = (buf) => { let n = 0n; for (let i = buf.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(buf[i]); return n; };
@@ -279,8 +328,8 @@ export function verifyNext(prev, m) {
279
328
  const t = m.transition;
280
329
  const needsRequest = t.action === "accept" || t.action === "leave";
281
330
  if (!row.actions.includes(t.action)) return no("transition-mismatch"); // @rule M1-transition-label
282
- if (t.actor !== pAdmin.uuaid || t.target !== row.target) return no("transition-mismatch");
283
- if (needsRequest ? !(typeof t.request === "string" && t.request.length > 0) : t.request !== null) return no("transition-mismatch");
331
+ if (t.actor !== pAdmin.uuaid || t.target !== row.target) return no("transition-mismatch"); // @rule M1-actor-target
332
+ if (needsRequest ? !(typeof t.request === "string" && t.request.length > 0) : t.request !== null) return no("transition-mismatch"); // @rule M1-request-null
284
333
  return { ok: true, action: t.action };
285
334
  }
286
335
 
@@ -374,6 +423,114 @@ export function signManifest(m, signer) {
374
423
  return { ...body, sig: { alg: "ed25519", keyId: id.uuaid ?? uuaidForKey(id.publicKeyHex), publicKey: id.publicKeyHex, signature } };
375
424
  }
376
425
 
426
+ // ───────────────────────────────────────────── Family A: ext.admins (WIRE-family-A-v1 §2, §4) ──
427
+ // Co-admins live only in the profile key `ext.admins`; the chain never names them as admins and the
428
+ // verifier never reads the key (§1: a co-admin's change is a creator-signed manifest, request null).
429
+ // Receivers read a malformed list as empty. The creator's builder refuses to sign one (§4).
430
+
431
+ const ADMINS_KEYS = ["v", "coAdmins"];
432
+ const CO_ADMIN_KEYS = ["uuaid", "powers"];
433
+ const strictlySorted = (xs) => xs.every((x, i) => i === 0 || xs[i - 1] < x);
434
+
435
+ /**
436
+ * The first §2 fault of `m.ext.admins`, or null. A manifest without the key has none (an empty list).
437
+ * Checked on every manifest: shape, then that each entry names a row of `m` that is not its admin.
438
+ * An entry whose row is not `active` is NOT a fault here: it is inert (coAdminsOf skips it), so a
439
+ * co-admin can still leave or be removed, one change per version (§2).
440
+ */
441
+ export function adminsFault(m) {
442
+ if (!plain(m?.ext) || !Object.hasOwn(m.ext, "admins")) return null;
443
+ const a = m.ext.admins;
444
+ if (!closed(a, ADMINS_KEYS, ADMINS_KEYS)) return "admins-keys"; // @rule FA-closed-top
445
+ if (a.v !== ADMINS_V) return "admins-version"; // @rule FA-version
446
+ if (!Array.isArray(a.coAdmins)) return "admins-list"; // @rule FA-list
447
+ if (a.coAdmins.length > MAX_CO_ADMINS) return "admins-too-many"; // @rule FA-max-entries
448
+ for (const e of a.coAdmins) {
449
+ if (!closed(e, CO_ADMIN_KEYS, CO_ADMIN_KEYS)) return "admins-entry-keys"; // @rule FA-closed-entry
450
+ if (typeof e.uuaid !== "string" || !UUAID_RE.test(e.uuaid)) return "admins-uuaid"; // @rule FA-entry-uuaid
451
+ if (!Array.isArray(e.powers) || e.powers.length === 0) return "admins-no-powers"; // @rule FA-powers-non-empty
452
+ if (!e.powers.every((p) => CO_ADMIN_POWERS.includes(p))) return "admins-power"; // @rule FA-powers-closed
453
+ if (!strictlySorted(e.powers)) return "admins-powers-order"; // @rule FA-powers-sorted
454
+ }
455
+ if (!strictlySorted(a.coAdmins.map((e) => e.uuaid))) return "admins-order"; // @rule FA-entries-sorted
456
+ const admin = adminOf(m)?.uuaid;
457
+ for (const e of a.coAdmins) {
458
+ if (!m.members.some((r) => r.uuaid === e.uuaid)) return "admins-non-member"; // @rule FA-entry-is-member
459
+ if (e.uuaid === admin) return "admins-admin-listed"; // @rule FA-entry-not-admin
460
+ }
461
+ return null;
462
+ }
463
+
464
+ /** uuaid -> its powers, for each co-admin of `m` whose row is `active`. Empty for a malformed list (§2). */
465
+ export function coAdminsOf(m) {
466
+ const out = new Map();
467
+ if (adminsFault(m)) return out; // @rule FA-malformed-is-empty
468
+ for (const e of m.ext.admins?.coAdmins ?? []) {
469
+ if (m.members.find((r) => r.uuaid === e.uuaid)?.status !== "active") continue; // @rule FA-inert-entry
470
+ out.set(e.uuaid, [...e.powers]);
471
+ }
472
+ return out;
473
+ }
474
+
475
+ /** Actions the builder still signs over an inherited malformed list it leaves byte-identical (§4, Lead ruling OPEN-3). */
476
+ const SIGN_OVER_INHERITED_DAMAGE = Object.freeze(["remove", "leave"]);
477
+
478
+ /**
479
+ * §4 builder refusal: the fault that forbids signing `next` (version 1 when `prev` is null), or null.
480
+ * - Inherited damage (Lead ruling OPEN-3): when `prev` already carries a malformed list and `next` keeps
481
+ * `ext.admins` byte-identical, only `remove` and the fold of a `leave.request` are signed (the list
482
+ * already reads as empty everywhere; blocking `remove` would stop the owner removing a member). Every
483
+ * other action waits for the repairing `ext_update`, which changes `ext.admins` and takes the path below.
484
+ * - Every other build needs a well-formed list (adminsFault).
485
+ * - No power revival (Lead ruling OPEN-1): an `invite` or `accept` whose target is listed in the head's
486
+ * `ext.admins` is refused; the owner unmakes the entry first.
487
+ * - A build that changes `ext.admins` (the owner's make- or unmake-admin click) also needs every listed
488
+ * member `active` and every other `ext` key unchanged.
489
+ */
490
+ export function adminsSigningFault(prev, next) {
491
+ const before = plain(prev?.ext) ? prev.ext.admins : undefined;
492
+ const after = next.ext.admins;
493
+ let unchanged = canonicalJson(before ?? null) === canonicalJson(after ?? null);
494
+ // 2.8.2 r2 (RedTeam 822828 P3): a present `admins: null` and a missing key differ; removing the field repairs it.
495
+ const listed = (ext) => plain(ext) && Object.hasOwn(ext, "admins");
496
+ if (listed(prev?.ext) !== listed(next.ext)) unchanged = false; // @t282 m1-presence
497
+ const inherited = prev ? adminsFault(prev) : null;
498
+ if (inherited && unchanged) {
499
+ return SIGN_OVER_INHERITED_DAMAGE.includes(next.transition?.action) ? null : "admins-repair-first"; // @rule FA-inherited-damage
500
+ }
501
+ const fault = adminsFault(next);
502
+ if (fault) return fault;
503
+ const action = next.transition?.action;
504
+ if ((action === "invite" || action === "accept") && (before?.coAdmins ?? []).some((e) => e?.uuaid === next.transition.target)) {
505
+ return "admins-target-listed"; // @rule FA-no-power-revival
506
+ }
507
+ if (unchanged) return null;
508
+ for (const e of after?.coAdmins ?? []) {
509
+ if (next.members.find((r) => r.uuaid === e.uuaid)?.status !== "active") return "admins-not-active"; // @rule FA-set-active-only
510
+ }
511
+ const rest = (x) => canonicalJson(without(plain(x) ? x : {}, "admins"));
512
+ if (prev && rest(prev.ext) !== rest(next.ext)) return "admins-other-ext-changed"; // @rule FA-other-ext-kept
513
+ return null;
514
+ }
515
+
516
+ /** Throws, before any signature, when adminsSigningFault forbids signing `next` (§4: nothing is sent). */
517
+ function assertAdminsSignable(prev, next) {
518
+ const fault = adminsSigningFault(prev, next);
519
+ if (fault) throw Object.assign(new Error(`refusing to sign version ${next.version}: ext.admins ${fault}`), { code: "group-v2-admins-refused", fault });
520
+ }
521
+
522
+ /**
523
+ * The optional binding body of a `rename.request` (§3): `{ name, purpose }` (purpose a string or null),
524
+ * or null when absent or malformed. Null leaves the request a suggestion, as before Family A.
525
+ */
526
+ export function parseRenameField(payload) {
527
+ const r = plain(payload) ? payload.rename : undefined;
528
+ if (!closed(r, ["name", "purpose"], ["name", "purpose"])) return null;
529
+ if (typeof r.name !== "string" || r.name.trim() === "" || codePoints(r.name) > MAX_NAME) return null; // @rule FA-rename-name
530
+ if (!(r.purpose === null || (typeof r.purpose === "string" && codePoints(r.purpose) <= MAX_PURPOSE))) return null;
531
+ return { name: r.name, purpose: r.purpose };
532
+ }
533
+
377
534
  // ───────────────────────────────────────────── store (pillar-group-store/2) ──
378
535
 
379
536
  /** A store record is fine only if its chain verifies and its head matches. */
@@ -520,9 +677,12 @@ export function reconcileMailboxRosters(store, mailbox, selfUuaid) {
520
677
  * Create a group: sign version 1 with `keychain`, verify it, store it, then
521
678
  * write the mailbox row. `members`: [{ uuaid, key }], each invited.
522
679
  */
523
- export function adminCreate({ store, mailbox, keychain, name, purpose, members = [] }) {
680
+ export function adminCreate({ store, mailbox, keychain, name, purpose, members = [], ext = {} }) {
681
+ ext = boundedJsonRecord(ext, MAX_MANIFEST_BYTES);
524
682
  const me = keychain._identity;
525
- const g = signManifest(buildGenesis({ name, purpose, creator: { uuaid: me.uuaid, publicKeyHex: me.publicKeyHex }, members }), keychain);
683
+ const built = buildGenesis({ name, purpose, creator: { uuaid: me.uuaid, publicKeyHex: me.publicKeyHex }, members, ext });
684
+ assertAdminsSignable(null, built); // @rule FA-builder-refuses-genesis
685
+ const g = signManifest(built, keychain);
526
686
  const v = verifyGenesis(g);
527
687
  if (!v.ok) throw new Error(`refusing to store a genesis that does not verify: ${v.reason}`);
528
688
  const rec = newRecord([g]);
@@ -540,7 +700,9 @@ export function adminChange({ store, mailbox, keychain, groupId, action, opts =
540
700
  const rec = loadGroupForCommand(store, groupId);
541
701
  if (rec.frozen) throw new Error(`${groupId} is frozen (equivocation); a frozen group can only be replaced by a new group`);
542
702
  const head = rec.chain[rec.chain.length - 1];
543
- const next = signManifest(buildNext(head, action, opts), keychain);
703
+ const built = buildNext(head, action, opts);
704
+ assertAdminsSignable(head, built); // @rule FA-builder-refuses
705
+ const next = signManifest(built, keychain);
544
706
  const v = verifyNext(head, next);
545
707
  if (!v.ok) throw new Error(`refusing to store version ${next.version}: ${v.reason}`);
546
708
  rec.chain.push(next);
@@ -696,6 +858,23 @@ function badTag(g) {
696
858
  return null;
697
859
  }
698
860
 
861
+ /**
862
+ * Family A bodies (§3), beside `text` and `_group` in the payload: the first malformed one, or null.
863
+ * Reported as `detail` with bad-group-message. `rename` on rename.request is optional and never
864
+ * drops a message: parseRenameField reads it, and a malformed one leaves a suggestion.
865
+ */
866
+ function badBody(p, op) {
867
+ if (op === "invite.request") {
868
+ const i = p.invite;
869
+ if (!closed(i, ["uuaid", "key"], ["uuaid", "key"]) || typeof i.uuaid !== "string" || !UUAID_RE.test(i.uuaid) || typeof i.key !== "string" || !HEX64.test(i.key)) return "invite";
870
+ }
871
+ if (op === "request.refused") {
872
+ const r = p.refused;
873
+ if (!closed(r, ["msgId", "reason"], ["msgId", "reason"]) || typeof r.msgId !== "string" || !MSGID_RE.test(r.msgId) || !REFUSE_REASONS.includes(r.reason)) return "refused";
874
+ }
875
+ return null;
876
+ }
877
+
699
878
  const res = (verdict, reason = null, extra = {}) => ({ verdict, reason, ...extra });
700
879
  const drop = (reason, extra) => res("dropped", reason, extra);
701
880
 
@@ -804,6 +983,8 @@ export class GroupReceiver {
804
983
  }
805
984
  const bad = badTag(g);
806
985
  if (bad) return drop("bad-group-message", { detail: bad }); // @rule R4-tag-shape
986
+ const badB = badBody(p, g.op);
987
+ if (badB) return drop("bad-group-message", { detail: badB }); // @rule FA-body-shape
807
988
  const rec = this._rec(g.id);
808
989
  if (!rec) return this._unknown(env, g, now, out);
809
990
  return this._judgeKnown(env, g, now, out);
@@ -871,6 +1052,10 @@ export class GroupReceiver {
871
1052
  // 7. Rule 3 under the receiver's own manifest: mv never widens authority.
872
1053
  const r3 = this._rule3(env, g, rec);
873
1054
  if (r3) return drop(r3);
1055
+ // Family A (§3): an invite.request goes to the creator only; a requester takes a refusal only from
1056
+ // the admin of its own current head. Whether the sender may ask is the creator app's call (§4).
1057
+ const fa = this._familyA(env, g, rec);
1058
+ if (fa) return drop(fa);
874
1059
  const k = this._seenKey(env.from, g.msgId);
875
1060
  if (rec.seen.has(k)) return drop("duplicate-msgid"); // @rule R3-msgid-dedupe
876
1061
  this._markSeen(rec, k);
@@ -881,6 +1066,14 @@ export class GroupReceiver {
881
1066
  return res("accepted");
882
1067
  }
883
1068
 
1069
+ /** Family A routing (§3). Null when the message may be accepted. */
1070
+ _familyA(env, g, rec) {
1071
+ const admin = adminOf(this._head(rec)).uuaid;
1072
+ if (g.op === "invite.request" && admin !== this.self.uuaid) return "request-not-for-admin"; // @rule FA-request-to-admin
1073
+ if (g.op === "request.refused" && env.from !== admin) return "refused-not-from-admin"; // @rule FA-refused-from-admin
1074
+ return null;
1075
+ }
1076
+
884
1077
  _effects(env, g, rec, out) {
885
1078
  const head = this._head(rec);
886
1079
  if (g.op === "leave.request" && !rec.leaving.includes(env.from)) {
@@ -385,6 +385,12 @@ export class Mailbox {
385
385
  ).run(carrier, seq);
386
386
  }
387
387
 
388
+ /** 2.8.3: forget one carrier's cursor (Pillar#setSeedRoutes drops a removed seed's). True when a row went. */
389
+ deleteCarrierCursor(carrier) {
390
+ if (this._jsonDir) return this._jsonDir.deleteCarrierCursor(carrier);
391
+ return this.db.prepare("delete from carrier_cursors where carrier = ?").run(carrier).changes > 0;
392
+ }
393
+
388
394
  _getHead(logName) {
389
395
  const row = this.db.prepare("select chain_head from chain_state where log_name = ?").get(logName);
390
396
  return row?.chain_head ?? null;
@@ -494,6 +500,15 @@ export class Mailbox {
494
500
  .run(new Date().toISOString(), ackSha256 ?? null, envelopeId);
495
501
  }
496
502
 
503
+ /**
504
+ * 2.8.2 r2: status 'superseded' for a live pending row that no SDK path will send again (a group v2 queue
505
+ * item moved to a new envelope, or ended). A carrier that holds a copy may still deliver it. Other rows: no-op.
506
+ */
507
+ markOutboundSuperseded(envelopeId) {
508
+ if (this._jsonDir) return this._jsonDir.markOutboundSuperseded(envelopeId);
509
+ this.db.prepare(`update outbox set status = 'superseded' where envelope_id = ? and status = 'pending' and ${LIVE_ENVELOPE_SQL}`).run(envelopeId);
510
+ }
511
+
497
512
  outboxTip() { return this._jsonDir ? this._jsonDir.outboxTip() : (this._getHead("outbox") ?? "0".repeat(64)); }
498
513
  inboxTip() { return this._jsonDir ? this._jsonDir.inboxTip() : (this._getHead("inbox") ?? "0".repeat(64)); }
499
514
 
@@ -733,11 +748,27 @@ export class Mailbox {
733
748
  : this.db.prepare("select * from group_v2_sendq where state = 'queued' order by queued_at, rowid").all();
734
749
  }
735
750
 
736
- /** state: sent | dropped (final), or queued with a reason (a failed attempt). */
737
- markGroupV2Send(id, state, { envelopeId = null, reason = null } = {}) {
738
- if (this._jsonDir) return this._jsonDir.markGroupV2Send(id, state, { envelopeId, reason });
739
- this.db.prepare("update group_v2_sendq set state = ?, state_at = ?, envelope_id = coalesce(?, envelope_id), reason = ? where id = ?")
740
- .run(state, new Date().toISOString(), envelopeId, reason ? String(reason).slice(0, 200) : null, id);
751
+ /**
752
+ * state: sent | dropped (final), or queued with a reason (a failed attempt). True when the row changed.
753
+ * 2.8.2 r4 (RedTeam 87e556): with `attempt` (an envelope id, or null before a first attempt), it writes only while
754
+ * the item is queued and still names that attempt: the owner check before syncGroupV2 records a result.
755
+ */
756
+ markGroupV2Send(id, state, { envelopeId = null, reason = null, attempt } = {}) {
757
+ if (this._jsonDir) return this._jsonDir.markGroupV2Send(id, state, { envelopeId, reason, attempt });
758
+ const owner = attempt === undefined ? "" : " and state = 'queued' and envelope_id is ?";
759
+ return this.db.prepare(`update group_v2_sendq set state = ?, state_at = ?, envelope_id = coalesce(?, envelope_id), reason = ? where id = ?${owner}`)
760
+ .run(state, new Date().toISOString(), envelopeId, reason ? String(reason).slice(0, 200) : null, id, ...(owner ? [attempt] : [])).changes === 1;
761
+ }
762
+
763
+ /**
764
+ * 2.8.2 r3 (RedTeam bcdc6c): claim a queued item's next attempt. It sets envelope_id to `next` only while the item
765
+ * is queued and still names `expected` (null before a first attempt). True when this caller won. A value swap, not
766
+ * a lock, so a crash leaves nothing held.
767
+ */
768
+ claimGroupV2Attempt(id, expected, next) {
769
+ if (this._jsonDir) return this._jsonDir.claimGroupV2Attempt(id, expected, next);
770
+ return this.db.prepare("update group_v2_sendq set envelope_id = ?, state_at = ? where id = ? and state = 'queued' and envelope_id is ?")
771
+ .run(next, new Date().toISOString(), id, expected ?? null).changes === 1;
741
772
  }
742
773
 
743
774
  /**