@serfab/cadre-core 1.13.0 → 1.14.0

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.
Files changed (120) hide show
  1. package/dist/cadre-invite-protocol.d.ts +348 -0
  2. package/dist/cadre-invite-protocol.js +605 -0
  3. package/dist/cadre-invite-protocol.js.map +1 -0
  4. package/dist/cadre-node.d.ts +523 -180
  5. package/dist/cadre-node.js +921 -293
  6. package/dist/cadre-node.js.map +1 -1
  7. package/dist/claim-proof.d.ts +45 -0
  8. package/dist/claim-proof.js +132 -0
  9. package/dist/claim-proof.js.map +1 -0
  10. package/dist/control-authorization.d.ts +80 -19
  11. package/dist/control-authorization.js +55 -13
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.js +1 -1
  14. package/dist/control-cohort.js.map +1 -1
  15. package/dist/control-database.d.ts +514 -97
  16. package/dist/control-database.js +1033 -195
  17. package/dist/control-database.js.map +1 -1
  18. package/dist/control-protocol-guard.d.ts +142 -0
  19. package/dist/control-protocol-guard.js +293 -0
  20. package/dist/control-protocol-guard.js.map +1 -0
  21. package/dist/control-schema.d.ts +1 -1
  22. package/dist/control-schema.js +801 -1067
  23. package/dist/control-schema.js.map +1 -1
  24. package/dist/control-stream.d.ts +4 -0
  25. package/dist/control-stream.js +22 -7
  26. package/dist/control-stream.js.map +1 -1
  27. package/dist/delegate-admission.d.ts +1 -1
  28. package/dist/delegate-admission.js +1 -1
  29. package/dist/device-token.d.ts +11 -9
  30. package/dist/device-token.js +14 -12
  31. package/dist/device-token.js.map +1 -1
  32. package/dist/ed25519-key.d.ts +15 -0
  33. package/dist/ed25519-key.js +28 -1
  34. package/dist/ed25519-key.js.map +1 -1
  35. package/dist/index.d.ts +14 -9
  36. package/dist/index.js +27 -9
  37. package/dist/index.js.map +1 -1
  38. package/dist/link-budget.d.ts +16 -29
  39. package/dist/link-budget.js +16 -31
  40. package/dist/link-budget.js.map +1 -1
  41. package/dist/membership-connection-gater.d.ts +190 -151
  42. package/dist/membership-connection-gater.js +235 -173
  43. package/dist/membership-connection-gater.js.map +1 -1
  44. package/dist/node-claim-payload.d.ts +19 -0
  45. package/dist/node-claim-payload.js +120 -0
  46. package/dist/node-claim-payload.js.map +1 -0
  47. package/dist/owner-anchor-sync.d.ts +22 -0
  48. package/dist/owner-anchor-sync.js +143 -0
  49. package/dist/owner-anchor-sync.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +113 -18
  51. package/dist/peer-authorization.js +225 -29
  52. package/dist/peer-authorization.js.map +1 -1
  53. package/dist/peer-dial.d.ts +19 -0
  54. package/dist/peer-dial.js +22 -1
  55. package/dist/peer-dial.js.map +1 -1
  56. package/dist/peer-join-backfill.d.ts +26 -2
  57. package/dist/peer-join-backfill.js +54 -12
  58. package/dist/peer-join-backfill.js.map +1 -1
  59. package/dist/peer-record.d.ts +13 -9
  60. package/dist/peer-record.js +16 -12
  61. package/dist/peer-record.js.map +1 -1
  62. package/dist/pending-join-runner.d.ts +66 -58
  63. package/dist/pending-join-runner.js +136 -145
  64. package/dist/pending-join-runner.js.map +1 -1
  65. package/dist/push-fanout.d.ts +8 -2
  66. package/dist/push-fanout.js +8 -2
  67. package/dist/push-fanout.js.map +1 -1
  68. package/dist/seed-bootstrap.d.ts +147 -122
  69. package/dist/seed-bootstrap.js +284 -269
  70. package/dist/seed-bootstrap.js.map +1 -1
  71. package/dist/seed-trust-policy.d.ts +98 -37
  72. package/dist/seed-trust-policy.js +188 -2
  73. package/dist/seed-trust-policy.js.map +1 -1
  74. package/dist/strand-addr-protocol.d.ts +24 -26
  75. package/dist/strand-addr-protocol.js +19 -26
  76. package/dist/strand-addr-protocol.js.map +1 -1
  77. package/dist/strand-formation-protocol.js +1 -1
  78. package/dist/strand-formation-protocol.js.map +1 -1
  79. package/dist/strand-revocation-enforcer.d.ts +11 -11
  80. package/dist/strand-revocation-enforcer.js +11 -11
  81. package/dist/strand-wake-protocol.d.ts +13 -16
  82. package/dist/strand-wake-protocol.js +13 -20
  83. package/dist/strand-wake-protocol.js.map +1 -1
  84. package/dist/trusted-owner-store.d.ts +35 -5
  85. package/dist/trusted-owner-store.js +50 -8
  86. package/dist/trusted-owner-store.js.map +1 -1
  87. package/dist/types.d.ts +302 -87
  88. package/dist/types.js.map +1 -1
  89. package/package.json +8 -7
  90. package/src/cadre-invite-protocol.ts +864 -0
  91. package/src/cadre-node.ts +9381 -8686
  92. package/src/claim-proof.ts +147 -0
  93. package/src/control-authorization.ts +203 -117
  94. package/src/control-cohort.ts +1 -1
  95. package/src/control-database.ts +1216 -218
  96. package/src/control-protocol-guard.ts +348 -0
  97. package/src/control-schema.ts +812 -1078
  98. package/src/control-stream.ts +26 -7
  99. package/src/delegate-admission.ts +1 -1
  100. package/src/device-token.ts +14 -10
  101. package/src/ed25519-key.ts +28 -1
  102. package/src/index.ts +84 -10
  103. package/src/link-budget.ts +16 -32
  104. package/src/membership-connection-gater.ts +637 -570
  105. package/src/node-claim-payload.ts +125 -0
  106. package/src/owner-anchor-sync.ts +171 -0
  107. package/src/peer-authorization.ts +258 -29
  108. package/src/peer-dial.ts +22 -1
  109. package/src/peer-join-backfill.ts +56 -11
  110. package/src/peer-record.ts +16 -11
  111. package/src/pending-join-runner.ts +729 -735
  112. package/src/push-fanout.ts +8 -2
  113. package/src/seed-bootstrap.ts +344 -321
  114. package/src/seed-trust-policy.ts +353 -140
  115. package/src/strand-addr-protocol.ts +26 -35
  116. package/src/strand-formation-protocol.ts +1 -1
  117. package/src/strand-revocation-enforcer.ts +11 -11
  118. package/src/strand-wake-protocol.ts +13 -23
  119. package/src/trusted-owner-store.ts +242 -171
  120. package/src/types.ts +2471 -2242
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The claim payload: what a host shows as a QR code (and as text) for a node that is
3
+ * waiting to be claimed, and what the owner's phone scans to claim it.
4
+ *
5
+ * `sereus-join:1.<base64url of canonical JSON>` where the JSON is
6
+ * `{ multiaddrs, peerId, secret }`: the node's peer id, every address the phone may
7
+ * dial it at (each ending in `/p2p/<peerId>`), and the node's one-time claim secret
8
+ * (`claim-proof.ts`). The phone hands all three to `CadreNode.claimNode`. The payload
9
+ * carries no party id: the claim supplies it, and the node records it.
10
+ *
11
+ * The decoder lives here, beside the encoder, because the phone and the host both need
12
+ * it and neither depends on the other. Imports only `@multiformats/multiaddr`,
13
+ * `@libp2p/peer-id` and `uint8arrays`, so it loads on React Native and in the browser.
14
+ */
15
+ import { peerIdFromString } from '@libp2p/peer-id';
16
+ import { multiaddr, CODE_P2P, CODE_P2P_CIRCUIT } from '@multiformats/multiaddr';
17
+ import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
18
+ import { canonicalJson } from './canonical-json.js';
19
+ import { parseClaimSecret } from './claim-proof.js';
20
+
21
+ /** Version 1 of the payload; the only one either side reads. */
22
+ export const NODE_CLAIM_PAYLOAD_PREFIX = 'sereus-join:1.';
23
+
24
+ export interface NodeClaimPayload {
25
+ /** The node's peer id. */
26
+ peerId: string;
27
+ /** Addresses the phone may dial the node at, each ending in `/p2p/<peerId>`. */
28
+ multiaddrs: string[];
29
+ /** The node's claim secret, base64url (`parseClaimSecret`). */
30
+ secret: string;
31
+ }
32
+
33
+ /** Encode a payload as the text the host shows. Refuses what {@link decodeNodeClaimPayload} would. */
34
+ export function encodeNodeClaimPayload(payload: NodeClaimPayload): string {
35
+ const checked = requireNodeClaimPayload(payload);
36
+ const json = canonicalJson({ multiaddrs: checked.multiaddrs, peerId: checked.peerId, secret: checked.secret });
37
+ return `${NODE_CLAIM_PAYLOAD_PREFIX}${uint8ArrayToString(new TextEncoder().encode(json), 'base64url')}`;
38
+ }
39
+
40
+ /**
41
+ * Decode the text a phone scanned or pasted. Refuses, naming the problem: any version but
42
+ * 1, a body that is not base64url JSON of the right shape, a peer id that does not parse,
43
+ * an empty address list, an address that does not parse or whose last `/p2p/` is not that
44
+ * peer id, and a secret {@link parseClaimSecret} refuses. The secret is never echoed.
45
+ */
46
+ export function decodeNodeClaimPayload(text: string): NodeClaimPayload {
47
+ const trimmed = text.trim();
48
+ if (!trimmed.startsWith(NODE_CLAIM_PAYLOAD_PREFIX)) {
49
+ throw new Error(`A claim payload must start with "${NODE_CLAIM_PAYLOAD_PREFIX}" (this one starts with "${trimmed.slice(0, NODE_CLAIM_PAYLOAD_PREFIX.length)}")`);
50
+ }
51
+ let parsed: unknown;
52
+ try {
53
+ const json = new TextDecoder().decode(uint8ArrayFromString(trimmed.slice(NODE_CLAIM_PAYLOAD_PREFIX.length), 'base64url'));
54
+ parsed = JSON.parse(json);
55
+ } catch (error) {
56
+ throw new Error('A claim payload must carry base64url-encoded JSON after its prefix', { cause: error });
57
+ }
58
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
59
+ throw new Error('A claim payload must decode to a JSON object');
60
+ }
61
+ const { peerId, multiaddrs, secret } = parsed as Record<string, unknown>;
62
+ if (typeof peerId !== 'string') throw new Error('A claim payload must name the node\'s peer id');
63
+ if (!Array.isArray(multiaddrs) || !multiaddrs.every((a): a is string => typeof a === 'string')) {
64
+ throw new Error('A claim payload must carry the node\'s addresses as a list of strings');
65
+ }
66
+ if (typeof secret !== 'string') throw new Error('A claim payload must carry the claim secret');
67
+ return requireNodeClaimPayload({ peerId, multiaddrs, secret });
68
+ }
69
+
70
+ /** The shape rules both directions apply. Returns the payload with its fields trimmed. */
71
+ function requireNodeClaimPayload(payload: NodeClaimPayload): NodeClaimPayload {
72
+ const peerId = parsePeerId(payload.peerId);
73
+ const multiaddrs = payload.multiaddrs.map((a) => a.trim());
74
+ if (multiaddrs.length === 0) throw new Error('A claim payload must carry at least one address for the node');
75
+ for (const addr of multiaddrs) requireAddressOf(addr, peerId);
76
+ // The secret is checked, never kept in a message: see `parseClaimSecret`.
77
+ parseClaimSecret(payload.secret);
78
+ return { peerId: peerId.toString(), multiaddrs, secret: payload.secret.trim() };
79
+ }
80
+
81
+ function parsePeerId(text: string): ReturnType<typeof peerIdFromString> {
82
+ try {
83
+ return peerIdFromString(text.trim());
84
+ } catch (error) {
85
+ throw new Error(`A claim payload's peer id does not parse ("${text}")`, { cause: error });
86
+ }
87
+ }
88
+
89
+ /** `addr` parses, and its destination (the last `/p2p/`, past any relay hop) is `peerId`. */
90
+ function requireAddressOf(addr: string, peerId: ReturnType<typeof peerIdFromString>): void {
91
+ let destination: string | null;
92
+ try {
93
+ destination = destinationPeerIdOf(addr);
94
+ } catch (error) {
95
+ throw new Error(`A claim payload address does not parse ("${addr}")`, { cause: error });
96
+ }
97
+ if (destination === null) {
98
+ throw new Error(`A claim payload address must end in /p2p/${peerId.toString()} ("${addr}" names no peer)`);
99
+ }
100
+ let named: ReturnType<typeof peerIdFromString>;
101
+ try {
102
+ named = peerIdFromString(destination);
103
+ } catch (error) {
104
+ throw new Error(`A claim payload address names a peer id that does not parse ("${addr}")`, { cause: error });
105
+ }
106
+ if (!named.equals(peerId)) {
107
+ throw new Error(`A claim payload address names another peer ("${addr}" is not an address of ${peerId.toString()})`);
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The peer an address reaches: its last `/p2p/` component. A relayed address
113
+ * (`…/p2p/<relay>/p2p-circuit/p2p/<destination>`) names its destination after the
114
+ * circuit hop; one that ends at the hop names nobody. Same rule as
115
+ * `groupAddrsByPeerId` in `peer-addr-book.ts`.
116
+ */
117
+ function destinationPeerIdOf(addr: string): string | null {
118
+ const components = multiaddr(addr).getComponents();
119
+ for (let i = components.length - 1; i >= 0; i--) {
120
+ const component = components[i]!;
121
+ if (component.code === CODE_P2P_CIRCUIT) return null;
122
+ if (component.code === CODE_P2P && component.value) return component.value;
123
+ }
124
+ return null;
125
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * How the node-local trusted-owner anchor follows the replicated `OwnerKey` table along
3
+ * VERIFIABLE chains — the pure rule, with no I/O, so it can be tested without a database.
4
+ * `CadreNode.syncOwnerAnchor` reads the table, the tombstones and the invitation chain,
5
+ * calls {@link deriveOwnerAnchor}, and applies the difference to the store.
6
+ *
7
+ * Why not simply trust the table: an empty local copy can seat any key through the
8
+ * schema's genesis branch and that row replicates (`docs/architecture.md` → "Node-local
9
+ * trusted-owner anchor"). So every node grows its anchor only through rows whose stored
10
+ * proof verifies against a key it already trusts, on every membership refresh. The terms
11
+ * used throughout:
12
+ *
13
+ * - **base**: the anchor's entries whose provenance is not `chain` (trusted out of band).
14
+ * - **live row**: an `OwnerKey` row whose stamp no tombstone retires.
15
+ * - **kept**: a `chain` entry that still has a live row. A derived entry is state, not
16
+ * recomputed from the base each pass: it entered through a proof that verified then, and
17
+ * it stays until its own row is retired or a verifiable tombstone removes it. This is what
18
+ * lets an owner rotate (A adds A', A' removes A): A' keeps its place after A's row is
19
+ * retired, although nothing could re-derive it from the remaining base.
20
+ * - **derivable from S**: a live row whose stored proof verifies against S — owner-signed
21
+ * (`vouchSig` set): `vouchOwner` is in S and `verifyOwnerKeyVoucher` holds;
22
+ * invitation-admitted (`vouchSig` null, `vouchUsage` set): `verifyInvitationOwnerAdmission`
23
+ * holds with S as the anchor. The founding row (all three null) is never derivable:
24
+ * founders enter anchors only out of band.
25
+ * - **derived**: the least fixpoint from base ∪ kept — add every key whose live row is
26
+ * derivable from what is already in the set, until nothing changes. **chainDerived** is the
27
+ * keys whose live row was derivable in this pass, base keys included.
28
+ * - **removed**: a key K in derived is removed when an `OwnerKey` tombstone names K, its
29
+ * signer is in derived and is not K, its stored signature verifies
30
+ * (`verifyRevocationSigner`), AND K is not in chainDerived. The last condition is what
31
+ * makes a re-add win over an older tombstone: a removed owner re-added under a fresh
32
+ * stamp has a live derivable row again, and the old stamp's tombstone no longer applies.
33
+ * - **target** = derived minus removed. If that would be empty, no removal is applied this
34
+ * pass (target = derived) and the refused removals are reported for the caller to log.
35
+ *
36
+ * Every tombstone is judged against the pass-start set (derived) at once, so the outcome
37
+ * does not depend on the order they are read in: a signer that is itself removed in this
38
+ * pass still counts, and a mutual removal of the last two owners is refused rather than
39
+ * decided by read order.
40
+ *
41
+ * An owner C that a removed owner B had added therefore stays where it was already derived
42
+ * (its row is live) and cannot be derived on a machine that never held it (the chain from
43
+ * that machine's base runs through B's retired row) until a remaining owner re-adds it or
44
+ * an invitation pins it there. The rotation case above is the same shape with C = A', so the
45
+ * two cannot be told apart from replicated state; keeping is the only rule under which a
46
+ * sole owner can rotate at all.
47
+ */
48
+ import { verifyInvitationOwnerAdmission, verifyOwnerKeyVoucher, verifyRevocationSigner } from './peer-authorization.js';
49
+ import type { TrustSource } from './trusted-owner-store.js';
50
+ import type { InvitationChain, OwnerKeyRow, RevocationRow } from './types.js';
51
+
52
+ export interface OwnerAnchorInputs {
53
+ /** The party whose table is being read; every stored proof is judged for it, so a voucher or tombstone signed for another party neither seats nor removes a key. */
54
+ partyId: string;
55
+ /** The anchor at the start of the pass, every key with its provenance (`TrustedOwnerStore.sources`). */
56
+ anchor: ReadonlyMap<string, TrustSource>;
57
+ /** `OwnerKey` rows as read; rows whose stamp a tombstone in `tombstones` retires are dropped here too. */
58
+ rows: readonly OwnerKeyRow[];
59
+ /** `Revocation` rows; only those with `tableName === 'OwnerKey'` are consulted. */
60
+ tombstones: readonly RevocationRow[];
61
+ /** The usage and invitation rows, when some owner row is invitation-admitted; null skips those rows. */
62
+ chain: InvitationChain | null;
63
+ }
64
+
65
+ export interface OwnerAnchorDerivation {
66
+ /** The keys the anchor should hold after this pass. */
67
+ target: ReadonlySet<string>;
68
+ /** Keys whose verifiable removal was NOT applied because the anchor would have emptied. */
69
+ refusedRemovals: readonly string[];
70
+ }
71
+
72
+ /** The rule above, as one pure function. */
73
+ export function deriveOwnerAnchor({ partyId, anchor, rows, tombstones, chain }: OwnerAnchorInputs): OwnerAnchorDerivation {
74
+ const ownerTombstones = tombstones.filter(tombstone => tombstone.tableName === 'OwnerKey');
75
+ // NOTE: a stamp is retired by any tombstone that names it, verified or not — the same
76
+ // reading `queryCadrePeers` and `getOwnerKeys` give the table. A forged tombstone can
77
+ // therefore prune a derived entry (its row goes) but never seat or keep one; if tombstone
78
+ // pollution is ever closed at the write side, judge retirement by the verified signer too.
79
+ const retired = new Set(ownerTombstones.map(tombstone => tombstone.stampId));
80
+ const liveRows = rows.filter(row => !retired.has(row.stampId));
81
+
82
+ const derived = passStartSet(anchor, liveRows);
83
+ const chainDerived = deriveFixpoint(partyId, derived, liveRows, chain);
84
+
85
+ const removed = removedKeys(partyId, derived, chainDerived, ownerTombstones);
86
+ if (removed.size > 0 && removed.size === derived.size) {
87
+ return { target: derived, refusedRemovals: Array.from(removed) };
88
+ }
89
+ const target = new Set(Array.from(derived).filter(key => !removed.has(key)));
90
+ return { target, refusedRemovals: [] };
91
+ }
92
+
93
+ /** base ∪ kept: every out-of-band entry, and every `chain` entry whose row is still live. */
94
+ function passStartSet(anchor: ReadonlyMap<string, TrustSource>, liveRows: readonly OwnerKeyRow[]): Set<string> {
95
+ const liveKeys = new Set(liveRows.map(row => row.key));
96
+ const start = new Set<string>();
97
+ for (const [key, source] of anchor) {
98
+ if (source !== 'chain' || liveKeys.has(key)) {
99
+ start.add(key);
100
+ }
101
+ }
102
+ return start;
103
+ }
104
+
105
+ /**
106
+ * Grow `derived` to the least fixpoint and return chainDerived: every key whose live row was
107
+ * derivable. A row is judged once its voucher is in the set, and settled either way then:
108
+ * trust only grows within a pass, and a proof that failed against a trusted voucher cannot
109
+ * pass later, so no row is verified twice.
110
+ */
111
+ function deriveFixpoint(partyId: string, derived: Set<string>, liveRows: readonly OwnerKeyRow[], chain: InvitationChain | null): Set<string> {
112
+ const chainDerived = new Set<string>();
113
+ const pending = new Set(liveRows);
114
+ let progress = true;
115
+ while (progress) {
116
+ progress = false;
117
+ for (const row of pending) {
118
+ if (row.vouchOwner === null || !derived.has(row.vouchOwner)) {
119
+ continue;
120
+ }
121
+ pending.delete(row);
122
+ if (proofVerifies(partyId, row, derived, chain)) {
123
+ chainDerived.add(row.key);
124
+ derived.add(row.key);
125
+ progress = true;
126
+ }
127
+ }
128
+ }
129
+ return chainDerived;
130
+ }
131
+
132
+ /** Does `row`'s stored proof verify against `trusted`, for `partyId`, by the kind of proof it carries (see the module doc)? */
133
+ function proofVerifies(partyId: string, row: OwnerKeyRow, trusted: ReadonlySet<string>, chain: InvitationChain | null): boolean {
134
+ if (row.vouchOwner === null) {
135
+ return false;
136
+ }
137
+ if (row.vouchSig !== null) {
138
+ return verifyOwnerKeyVoucher(partyId, row.key, row.stampId, row.vouchOwner, row.vouchSig);
139
+ }
140
+ if (row.vouchUsage === null) {
141
+ return false;
142
+ }
143
+ const usage = chain?.usages.get(row.vouchUsage);
144
+ const invite = usage === undefined ? undefined : chain?.invites.get(usage.inviteKey);
145
+ if (usage === undefined || invite === undefined) {
146
+ return false;
147
+ }
148
+ return verifyInvitationOwnerAdmission(partyId, row, usage, invite, key => trusted.has(key));
149
+ }
150
+
151
+ /**
152
+ * The keys of `derived` that a verifiable tombstone removes (see the module doc), every
153
+ * tombstone judged against the same pass-start set. A tombstone for a key outside `derived`
154
+ * changes nothing and is skipped before any signature work.
155
+ */
156
+ function removedKeys(partyId: string, derived: ReadonlySet<string>, chainDerived: ReadonlySet<string>, ownerTombstones: readonly RevocationRow[]): Set<string> {
157
+ const removed = new Set<string>();
158
+ for (const tombstone of ownerTombstones) {
159
+ const key = tombstone.rowKey;
160
+ if (!derived.has(key) || chainDerived.has(key) || removed.has(key)) {
161
+ continue;
162
+ }
163
+ if (tombstone.signerKey === key || !derived.has(tombstone.signerKey)) {
164
+ continue;
165
+ }
166
+ if (verifyRevocationSigner(partyId, tombstone)) {
167
+ removed.add(key);
168
+ }
169
+ }
170
+ return removed;
171
+ }