@serfab/cadre-core 0.10.0 → 0.11.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 (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -1303
@@ -1,134 +1,134 @@
1
- import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
2
- import { getPublicKey } from '@optimystic/quereus-plugin-crypto';
3
- import type { PrivateKey } from '@libp2p/interface';
4
-
5
- /**
6
- * An Ed25519 keypair expressed in the base64url form that
7
- * `@optimystic/quereus-plugin-crypto` (`sign`/`verify`/`getPublicKey`) consumes.
8
- * Generic bridge type — reused for owner keys, member keys, and any other
9
- * seed→public keypair the control/strand databases sign with.
10
- */
11
- export interface Ed25519KeyPair {
12
- /** 32-byte Ed25519 seed, base64url-encoded — the crypto-plugin private key. */
13
- privateKeyB64: string;
14
- /** 32-byte Ed25519 public key, base64url-encoded. */
15
- publicKeyB64: string;
16
- }
17
-
18
- /**
19
- * Bridge a libp2p Ed25519 private key into the base64url keypair used by the
20
- * control- and strand-database signing constraints.
21
- *
22
- * libp2p stores an Ed25519 private key as 64 raw bytes: the first 32 are the
23
- * seed (the actual scalar source), the last 32 are the public key — see
24
- * `@libp2p/crypto`'s `Ed25519PrivateKey`. `@optimystic/quereus-plugin-crypto`
25
- * (via `@noble/curves`) treats the 32-byte seed *as* the private key and
26
- * derives the public key from it with standard Ed25519. The two derivations
27
- * agree, so the node's peer identity and its signing key are one keypair:
28
- * `getPublicKey(privateKeyB64)` === `publicKeyB64`.
29
- *
30
- * @param privateKey - The node's libp2p Ed25519 private key.
31
- * @returns The base64url seed/public-key pair for signing operations.
32
- * @throws If the key is not Ed25519 or the raw bytes aren't the expected length.
33
- */
34
- export function ed25519KeyPairFromLibp2p(privateKey: PrivateKey): Ed25519KeyPair {
35
- if (privateKey.type !== 'Ed25519') {
36
- throw new Error(`ed25519KeyPairFromLibp2p requires an Ed25519 key, got ${privateKey.type}`);
37
- }
38
-
39
- const raw = privateKey.raw;
40
- if (raw.length !== 64) {
41
- throw new Error(`Expected a 64-byte Ed25519 raw private key (seed||public), got ${raw.length} bytes`);
42
- }
43
-
44
- const seed = raw.subarray(0, 32);
45
- const publicKeyRaw = privateKey.publicKey.raw;
46
- if (publicKeyRaw.length !== 32) {
47
- throw new Error(`Expected a 32-byte Ed25519 public key, got ${publicKeyRaw.length} bytes`);
48
- }
49
-
50
- return {
51
- privateKeyB64: uint8ArrayToString(seed, 'base64url'),
52
- publicKeyB64: uint8ArrayToString(publicKeyRaw, 'base64url'),
53
- };
54
- }
55
-
56
- /**
57
- * Derive the base64url Ed25519 public key from a base64url 32-byte private seed
58
- * — the same derivation the seed-bootstrap signer uses internally
59
- * (`SeedBootstrapService` constructor). Use this to enroll a standalone
60
- * (non-libp2p) key into the control DB before minting an invite, when the
61
- * key is *not* the node's peer identity (so `ed25519KeyPairFromLibp2p`,
62
- * which needs a libp2p key object, does not apply).
63
- *
64
- * @param privateKeyB64 - The base64url-encoded 32-byte Ed25519 seed.
65
- * @returns The base64url-encoded Ed25519 public key.
66
- */
67
- export function ed25519PublicKeyFromPrivate(privateKeyB64: string): string {
68
- return getPublicKey(privateKeyB64, 'ed25519', 'base64url', 'base64url') as string;
69
- }
70
-
71
- /** Longest rejected key value echoed back in an error — a real key is 43 base64url chars. */
72
- const REJECTED_VALUE_ECHO_LIMIT = 64;
73
-
74
- /**
75
- * Render a rejected value for an error message, capped: owner keys now reach this check
76
- * from remote-supplied fields (a `CadreInvite`'s `ownerKeys`, a donation request's
77
- * `ownerKeys`), so an unbounded echo would let a peer turn one junk string into a
78
- * megabyte of log line.
79
- */
80
- function describeRejected(value: string): string {
81
- return value.length <= REJECTED_VALUE_ECHO_LIMIT
82
- ? value
83
- : `${value.slice(0, REJECTED_VALUE_ECHO_LIMIT)}… (${value.length} chars)`;
84
- }
85
-
86
- /**
87
- * Reject a value that isn't shaped like a base64url-encoded 32-byte Ed25519 public key
88
- * before it reaches the control database, where a malformed key would otherwise sit
89
- * indistinguishable from a real one until some later, unrelated signature check fails.
90
- *
91
- * Trims first, reusing the blank-value message for an empty result so that case keeps its
92
- * existing wording instead of a confusing base64url error. Every rejection names the offending
93
- * value (capped, see {@link describeRejected}) — with several keys in one batch, the message is
94
- * the only thing that says WHICH one. Does not check the decoded bytes
95
- * are a valid point on the Ed25519 curve — a well-formed-but-off-curve key still fails
96
- * signature verification later exactly like any other wrong key.
97
- *
98
- * **This rule is restated once outside this package**, in `validateOwnerKey`
99
- * (`packages/cadre-provider/src/server/owner-key-validation.ts`): cadre-provider declares no
100
- * `workspace:` dependencies and validates `POST /containers` pins over `uint8arrays`
101
- * directly. Change the rule here and change it there — the copies are kept in step by
102
- * hand, since neither package can import the other's. Each side pins its own copy to the
103
- * same accept/reject table (`test/ed25519-key.spec.ts` here,
104
- * `create-container-owner-keys.test.ts` there), so a change fails the suite of the
105
- * package it was made in and lands the editor on this pointer.
106
- *
107
- * @param value - Candidate base64url-encoded Ed25519 public key.
108
- * @param label - Human-readable name of the field, used in error messages.
109
- * @returns The trimmed value, so callers write the same bytes they validated.
110
- */
111
- export function requireEd25519PublicKeyB64(value: string, label: string): string {
112
- const trimmed = value.trim();
113
- if (trimmed.length === 0) {
114
- throw new Error(`A ${label} is required (received an empty or whitespace-only value)`);
115
- }
116
-
117
- let decoded: Uint8Array;
118
- try {
119
- decoded = uint8ArrayFromString(trimmed, 'base64url');
120
- } catch (error) {
121
- throw new Error(
122
- `A ${label} must be a base64url-encoded Ed25519 public key (could not decode "${describeRejected(trimmed)}" as base64url)`,
123
- { cause: error },
124
- );
125
- }
126
-
127
- if (decoded.length !== 32) {
128
- throw new Error(
129
- `A ${label} must be a base64url-encoded 32-byte Ed25519 public key ("${describeRejected(trimmed)}" decoded to ${decoded.length} bytes)`,
130
- );
131
- }
132
-
133
- return trimmed;
134
- }
1
+ import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
2
+ import { getPublicKey } from '@optimystic/quereus-plugin-crypto';
3
+ import type { PrivateKey } from '@libp2p/interface';
4
+
5
+ /**
6
+ * An Ed25519 keypair expressed in the base64url form that
7
+ * `@optimystic/quereus-plugin-crypto` (`sign`/`verify`/`getPublicKey`) consumes.
8
+ * Generic bridge type — reused for owner keys, member keys, and any other
9
+ * seed→public keypair the control/strand databases sign with.
10
+ */
11
+ export interface Ed25519KeyPair {
12
+ /** 32-byte Ed25519 seed, base64url-encoded — the crypto-plugin private key. */
13
+ privateKeyB64: string;
14
+ /** 32-byte Ed25519 public key, base64url-encoded. */
15
+ publicKeyB64: string;
16
+ }
17
+
18
+ /**
19
+ * Bridge a libp2p Ed25519 private key into the base64url keypair used by the
20
+ * control- and strand-database signing constraints.
21
+ *
22
+ * libp2p stores an Ed25519 private key as 64 raw bytes: the first 32 are the
23
+ * seed (the actual scalar source), the last 32 are the public key — see
24
+ * `@libp2p/crypto`'s `Ed25519PrivateKey`. `@optimystic/quereus-plugin-crypto`
25
+ * (via `@noble/curves`) treats the 32-byte seed *as* the private key and
26
+ * derives the public key from it with standard Ed25519. The two derivations
27
+ * agree, so the node's peer identity and its signing key are one keypair:
28
+ * `getPublicKey(privateKeyB64)` === `publicKeyB64`.
29
+ *
30
+ * @param privateKey - The node's libp2p Ed25519 private key.
31
+ * @returns The base64url seed/public-key pair for signing operations.
32
+ * @throws If the key is not Ed25519 or the raw bytes aren't the expected length.
33
+ */
34
+ export function ed25519KeyPairFromLibp2p(privateKey: PrivateKey): Ed25519KeyPair {
35
+ if (privateKey.type !== 'Ed25519') {
36
+ throw new Error(`ed25519KeyPairFromLibp2p requires an Ed25519 key, got ${privateKey.type}`);
37
+ }
38
+
39
+ const raw = privateKey.raw;
40
+ if (raw.length !== 64) {
41
+ throw new Error(`Expected a 64-byte Ed25519 raw private key (seed||public), got ${raw.length} bytes`);
42
+ }
43
+
44
+ const seed = raw.subarray(0, 32);
45
+ const publicKeyRaw = privateKey.publicKey.raw;
46
+ if (publicKeyRaw.length !== 32) {
47
+ throw new Error(`Expected a 32-byte Ed25519 public key, got ${publicKeyRaw.length} bytes`);
48
+ }
49
+
50
+ return {
51
+ privateKeyB64: uint8ArrayToString(seed, 'base64url'),
52
+ publicKeyB64: uint8ArrayToString(publicKeyRaw, 'base64url'),
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Derive the base64url Ed25519 public key from a base64url 32-byte private seed
58
+ * — the same derivation the seed-bootstrap signer uses internally
59
+ * (`SeedBootstrapService` constructor). Use this to enroll a standalone
60
+ * (non-libp2p) key into the control DB before minting an invite, when the
61
+ * key is *not* the node's peer identity (so `ed25519KeyPairFromLibp2p`,
62
+ * which needs a libp2p key object, does not apply).
63
+ *
64
+ * @param privateKeyB64 - The base64url-encoded 32-byte Ed25519 seed.
65
+ * @returns The base64url-encoded Ed25519 public key.
66
+ */
67
+ export function ed25519PublicKeyFromPrivate(privateKeyB64: string): string {
68
+ return getPublicKey(privateKeyB64, 'ed25519', 'base64url', 'base64url') as string;
69
+ }
70
+
71
+ /** Longest rejected key value echoed back in an error — a real key is 43 base64url chars. */
72
+ const REJECTED_VALUE_ECHO_LIMIT = 64;
73
+
74
+ /**
75
+ * Render a rejected value for an error message, capped: owner keys now reach this check
76
+ * from remote-supplied fields (a `CadreInvite`'s `ownerKeys`, a donation request's
77
+ * `ownerKeys`), so an unbounded echo would let a peer turn one junk string into a
78
+ * megabyte of log line.
79
+ */
80
+ function describeRejected(value: string): string {
81
+ return value.length <= REJECTED_VALUE_ECHO_LIMIT
82
+ ? value
83
+ : `${value.slice(0, REJECTED_VALUE_ECHO_LIMIT)}… (${value.length} chars)`;
84
+ }
85
+
86
+ /**
87
+ * Reject a value that isn't shaped like a base64url-encoded 32-byte Ed25519 public key
88
+ * before it reaches the control database, where a malformed key would otherwise sit
89
+ * indistinguishable from a real one until some later, unrelated signature check fails.
90
+ *
91
+ * Trims first, reusing the blank-value message for an empty result so that case keeps its
92
+ * existing wording instead of a confusing base64url error. Every rejection names the offending
93
+ * value (capped, see {@link describeRejected}) — with several keys in one batch, the message is
94
+ * the only thing that says WHICH one. Does not check the decoded bytes
95
+ * are a valid point on the Ed25519 curve — a well-formed-but-off-curve key still fails
96
+ * signature verification later exactly like any other wrong key.
97
+ *
98
+ * **This rule is restated once outside this package**, in `validateOwnerKey`
99
+ * (`packages/cadre-provider/src/server/owner-key-validation.ts`): cadre-provider declares no
100
+ * `workspace:` dependencies and validates `POST /containers` pins over `uint8arrays`
101
+ * directly. Change the rule here and change it there — the copies are kept in step by
102
+ * hand, since neither package can import the other's. Each side pins its own copy to the
103
+ * same accept/reject table (`test/ed25519-key.spec.ts` here,
104
+ * `create-container-owner-keys.test.ts` there), so a change fails the suite of the
105
+ * package it was made in and lands the editor on this pointer.
106
+ *
107
+ * @param value - Candidate base64url-encoded Ed25519 public key.
108
+ * @param label - Human-readable name of the field, used in error messages.
109
+ * @returns The trimmed value, so callers write the same bytes they validated.
110
+ */
111
+ export function requireEd25519PublicKeyB64(value: string, label: string): string {
112
+ const trimmed = value.trim();
113
+ if (trimmed.length === 0) {
114
+ throw new Error(`A ${label} is required (received an empty or whitespace-only value)`);
115
+ }
116
+
117
+ let decoded: Uint8Array;
118
+ try {
119
+ decoded = uint8ArrayFromString(trimmed, 'base64url');
120
+ } catch (error) {
121
+ throw new Error(
122
+ `A ${label} must be a base64url-encoded Ed25519 public key (could not decode "${describeRejected(trimmed)}" as base64url)`,
123
+ { cause: error },
124
+ );
125
+ }
126
+
127
+ if (decoded.length !== 32) {
128
+ throw new Error(
129
+ `A ${label} must be a base64url-encoded 32-byte Ed25519 public key ("${describeRejected(trimmed)}" decoded to ${decoded.length} bytes)`,
130
+ );
131
+ }
132
+
133
+ return trimmed;
134
+ }
package/src/enrollment.ts CHANGED
@@ -1,199 +1,199 @@
1
- import debug from 'debug';
2
- import { generateKeyPair, privateKeyToProtobuf } from '@libp2p/crypto/keys';
3
- import { peerIdFromPrivateKey } from '@libp2p/peer-id';
4
- import type {
5
- CreatePeerResult,
6
- MemberRegistration,
7
- MemberRegistrationResult
8
- } from './types.js';
9
-
10
- const log = debug('sereus:cadre:enrollment');
11
-
12
- /**
13
- * Interface for verifying member signatures for strand joining
14
- */
15
- export interface MemberVerifier {
16
- /**
17
- * Verify that the signature is valid for the given member registration
18
- * @param registration The member registration data
19
- * @param signature The signature to verify
20
- * @returns true if signature is valid
21
- */
22
- verifyMember(registration: MemberRegistration, signature: string): Promise<boolean>;
23
-
24
- /**
25
- * Check if the member key is authorized to join the strand
26
- * (e.g., was invited via FormationInvite)
27
- */
28
- isAuthorizedToJoin(strandId: string, memberKey: string): Promise<boolean>;
29
- }
30
-
31
- /**
32
- * Interface for registering members in a strand
33
- */
34
- export interface MemberRegistry {
35
- /**
36
- * Register a member in the strand's member list
37
- */
38
- registerMember(strandId: string, memberKey: string, peerIds: string[]): Promise<void>;
39
-
40
- /**
41
- * Check if a member is already registered in the strand
42
- */
43
- isMemberRegistered(strandId: string, memberKey: string): Promise<boolean>;
44
- }
45
-
46
- /**
47
- * Enrollment API for creating peer identities and managing strand membership
48
- *
49
- * Peer Creation:
50
- * `createCadrePeer()` generates an Ed25519 keypair for a new node.
51
- * For cadre peer authorization, use the Seed Bootstrap API instead.
52
- *
53
- * Member Registration:
54
- * Accept invitations to join strands as a member.
55
- */
56
- export class EnrollmentService {
57
- private readonly memberVerifier?: MemberVerifier;
58
- private readonly memberRegistry?: MemberRegistry;
59
-
60
- constructor(options?: {
61
- memberVerifier?: MemberVerifier;
62
- memberRegistry?: MemberRegistry;
63
- }) {
64
- this.memberVerifier = options?.memberVerifier;
65
- this.memberRegistry = options?.memberRegistry;
66
- log('EnrollmentService created');
67
- }
68
-
69
- /**
70
- * Create a new cadre peer identity
71
- *
72
- * Generates a new Ed25519 keypair for a cadre node.
73
- * The private key should be stored securely by the node.
74
- * The PeerId can be used with the Seed Bootstrap API for authorization.
75
- */
76
- async createCadrePeer(): Promise<CreatePeerResult> {
77
- log('Creating new cadre peer identity');
78
-
79
- // Generate Ed25519 keypair (same as libp2p uses)
80
- const privateKey = await generateKeyPair('Ed25519');
81
- const peerId = peerIdFromPrivateKey(privateKey);
82
-
83
- // Export private key as protobuf bytes for storage
84
- const privateKeyBytes = privateKeyToProtobuf(privateKey);
85
-
86
- log('Created peer with ID: %s', peerId.toString());
87
-
88
- return {
89
- peerId,
90
- privateKey: privateKeyBytes
91
- };
92
- }
93
-
94
- // ============================================================================
95
- // Member Registration API
96
- // ============================================================================
97
-
98
- /**
99
- * Register a member into a strand.
100
- *
101
- * Called by an invited party to accept an invitation and join as a member.
102
- * The signature proves ownership of the member key.
103
- *
104
- * @param registration The member registration data (strandId, key, peerIds)
105
- * @param signature Signature over the registration proving key ownership
106
- * @returns Success/failure with optional reason
107
- */
108
- async registerMember(
109
- registration: MemberRegistration,
110
- signature: string
111
- ): Promise<MemberRegistrationResult> {
112
- const { strandId, key, peerIds } = registration;
113
-
114
- log('Registering member %s for strand %s with %d peers', key, strandId, peerIds.length);
115
-
116
- // Check required dependencies
117
- if (!this.memberVerifier) {
118
- log('MemberVerifier not configured');
119
- return { success: false, reason: 'MemberVerifier not configured' };
120
- }
121
-
122
- if (!this.memberRegistry) {
123
- log('MemberRegistry not configured');
124
- return { success: false, reason: 'MemberRegistry not configured' };
125
- }
126
-
127
- // Verify the signature
128
- const isValidSignature = await this.memberVerifier.verifyMember(registration, signature);
129
- if (!isValidSignature) {
130
- log('Invalid signature for member registration: %s', key);
131
- return { success: false, reason: 'Invalid signature' };
132
- }
133
-
134
- // Check if member is authorized to join (e.g., has a valid invitation)
135
- const isAuthorized = await this.memberVerifier.isAuthorizedToJoin(strandId, key);
136
- if (!isAuthorized) {
137
- log('Member %s not authorized to join strand %s', key, strandId);
138
- return { success: false, reason: 'Not authorized to join strand' };
139
- }
140
-
141
- // Check if already registered
142
- const alreadyRegistered = await this.memberRegistry.isMemberRegistered(strandId, key);
143
- if (alreadyRegistered) {
144
- log('Member %s already registered in strand %s', key, strandId);
145
- return { success: false, reason: 'Member already registered' };
146
- }
147
-
148
- // Register the member
149
- try {
150
- await this.memberRegistry.registerMember(strandId, key, peerIds);
151
- log('Member %s successfully registered in strand %s', key, strandId);
152
- return { success: true };
153
- } catch (error) {
154
- const message = error instanceof Error ? error.message : String(error);
155
- log('Failed to register member %s: %s', key, message);
156
- return { success: false, reason: `Registration failed: ${message}` };
157
- }
158
- }
159
-
160
- /**
161
- * Validate a member registration without actually registering
162
- * Useful for pre-flight checks
163
- */
164
- async validateMemberRegistration(
165
- registration: MemberRegistration,
166
- signature: string
167
- ): Promise<{ valid: boolean; reason?: string }> {
168
- const { strandId, key } = registration;
169
-
170
- if (!this.memberVerifier) {
171
- return { valid: false, reason: 'MemberVerifier not configured' };
172
- }
173
-
174
- if (!this.memberRegistry) {
175
- return { valid: false, reason: 'MemberRegistry not configured' };
176
- }
177
-
178
- // Verify signature
179
- const isValidSignature = await this.memberVerifier.verifyMember(registration, signature);
180
- if (!isValidSignature) {
181
- return { valid: false, reason: 'Invalid signature' };
182
- }
183
-
184
- // Check authorization
185
- const isAuthorized = await this.memberVerifier.isAuthorizedToJoin(strandId, key);
186
- if (!isAuthorized) {
187
- return { valid: false, reason: 'Not authorized to join strand' };
188
- }
189
-
190
- // Check if already registered
191
- const alreadyRegistered = await this.memberRegistry.isMemberRegistered(strandId, key);
192
- if (alreadyRegistered) {
193
- return { valid: false, reason: 'Member already registered' };
194
- }
195
-
196
- return { valid: true };
197
- }
198
- }
199
-
1
+ import debug from 'debug';
2
+ import { generateKeyPair, privateKeyToProtobuf } from '@libp2p/crypto/keys';
3
+ import { peerIdFromPrivateKey } from '@libp2p/peer-id';
4
+ import type {
5
+ CreatePeerResult,
6
+ MemberRegistration,
7
+ MemberRegistrationResult
8
+ } from './types.js';
9
+
10
+ const log = debug('sereus:cadre:enrollment');
11
+
12
+ /**
13
+ * Interface for verifying member signatures for strand joining
14
+ */
15
+ export interface MemberVerifier {
16
+ /**
17
+ * Verify that the signature is valid for the given member registration
18
+ * @param registration The member registration data
19
+ * @param signature The signature to verify
20
+ * @returns true if signature is valid
21
+ */
22
+ verifyMember(registration: MemberRegistration, signature: string): Promise<boolean>;
23
+
24
+ /**
25
+ * Check if the member key is authorized to join the strand
26
+ * (e.g., was invited via FormationInvite)
27
+ */
28
+ isAuthorizedToJoin(strandId: string, memberKey: string): Promise<boolean>;
29
+ }
30
+
31
+ /**
32
+ * Interface for registering members in a strand
33
+ */
34
+ export interface MemberRegistry {
35
+ /**
36
+ * Register a member in the strand's member list
37
+ */
38
+ registerMember(strandId: string, memberKey: string, peerIds: string[]): Promise<void>;
39
+
40
+ /**
41
+ * Check if a member is already registered in the strand
42
+ */
43
+ isMemberRegistered(strandId: string, memberKey: string): Promise<boolean>;
44
+ }
45
+
46
+ /**
47
+ * Enrollment API for creating peer identities and managing strand membership
48
+ *
49
+ * Peer Creation:
50
+ * `createCadrePeer()` generates an Ed25519 keypair for a new node.
51
+ * For cadre peer authorization, use the Seed Bootstrap API instead.
52
+ *
53
+ * Member Registration:
54
+ * Accept invitations to join strands as a member.
55
+ */
56
+ export class EnrollmentService {
57
+ private readonly memberVerifier?: MemberVerifier;
58
+ private readonly memberRegistry?: MemberRegistry;
59
+
60
+ constructor(options?: {
61
+ memberVerifier?: MemberVerifier;
62
+ memberRegistry?: MemberRegistry;
63
+ }) {
64
+ this.memberVerifier = options?.memberVerifier;
65
+ this.memberRegistry = options?.memberRegistry;
66
+ log('EnrollmentService created');
67
+ }
68
+
69
+ /**
70
+ * Create a new cadre peer identity
71
+ *
72
+ * Generates a new Ed25519 keypair for a cadre node.
73
+ * The private key should be stored securely by the node.
74
+ * The PeerId can be used with the Seed Bootstrap API for authorization.
75
+ */
76
+ async createCadrePeer(): Promise<CreatePeerResult> {
77
+ log('Creating new cadre peer identity');
78
+
79
+ // Generate Ed25519 keypair (same as libp2p uses)
80
+ const privateKey = await generateKeyPair('Ed25519');
81
+ const peerId = peerIdFromPrivateKey(privateKey);
82
+
83
+ // Export private key as protobuf bytes for storage
84
+ const privateKeyBytes = privateKeyToProtobuf(privateKey);
85
+
86
+ log('Created peer with ID: %s', peerId.toString());
87
+
88
+ return {
89
+ peerId,
90
+ privateKey: privateKeyBytes
91
+ };
92
+ }
93
+
94
+ // ============================================================================
95
+ // Member Registration API
96
+ // ============================================================================
97
+
98
+ /**
99
+ * Register a member into a strand.
100
+ *
101
+ * Called by an invited party to accept an invitation and join as a member.
102
+ * The signature proves ownership of the member key.
103
+ *
104
+ * @param registration The member registration data (strandId, key, peerIds)
105
+ * @param signature Signature over the registration proving key ownership
106
+ * @returns Success/failure with optional reason
107
+ */
108
+ async registerMember(
109
+ registration: MemberRegistration,
110
+ signature: string
111
+ ): Promise<MemberRegistrationResult> {
112
+ const { strandId, key, peerIds } = registration;
113
+
114
+ log('Registering member %s for strand %s with %d peers', key, strandId, peerIds.length);
115
+
116
+ // Check required dependencies
117
+ if (!this.memberVerifier) {
118
+ log('MemberVerifier not configured');
119
+ return { success: false, reason: 'MemberVerifier not configured' };
120
+ }
121
+
122
+ if (!this.memberRegistry) {
123
+ log('MemberRegistry not configured');
124
+ return { success: false, reason: 'MemberRegistry not configured' };
125
+ }
126
+
127
+ // Verify the signature
128
+ const isValidSignature = await this.memberVerifier.verifyMember(registration, signature);
129
+ if (!isValidSignature) {
130
+ log('Invalid signature for member registration: %s', key);
131
+ return { success: false, reason: 'Invalid signature' };
132
+ }
133
+
134
+ // Check if member is authorized to join (e.g., has a valid invitation)
135
+ const isAuthorized = await this.memberVerifier.isAuthorizedToJoin(strandId, key);
136
+ if (!isAuthorized) {
137
+ log('Member %s not authorized to join strand %s', key, strandId);
138
+ return { success: false, reason: 'Not authorized to join strand' };
139
+ }
140
+
141
+ // Check if already registered
142
+ const alreadyRegistered = await this.memberRegistry.isMemberRegistered(strandId, key);
143
+ if (alreadyRegistered) {
144
+ log('Member %s already registered in strand %s', key, strandId);
145
+ return { success: false, reason: 'Member already registered' };
146
+ }
147
+
148
+ // Register the member
149
+ try {
150
+ await this.memberRegistry.registerMember(strandId, key, peerIds);
151
+ log('Member %s successfully registered in strand %s', key, strandId);
152
+ return { success: true };
153
+ } catch (error) {
154
+ const message = error instanceof Error ? error.message : String(error);
155
+ log('Failed to register member %s: %s', key, message);
156
+ return { success: false, reason: `Registration failed: ${message}` };
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Validate a member registration without actually registering
162
+ * Useful for pre-flight checks
163
+ */
164
+ async validateMemberRegistration(
165
+ registration: MemberRegistration,
166
+ signature: string
167
+ ): Promise<{ valid: boolean; reason?: string }> {
168
+ const { strandId, key } = registration;
169
+
170
+ if (!this.memberVerifier) {
171
+ return { valid: false, reason: 'MemberVerifier not configured' };
172
+ }
173
+
174
+ if (!this.memberRegistry) {
175
+ return { valid: false, reason: 'MemberRegistry not configured' };
176
+ }
177
+
178
+ // Verify signature
179
+ const isValidSignature = await this.memberVerifier.verifyMember(registration, signature);
180
+ if (!isValidSignature) {
181
+ return { valid: false, reason: 'Invalid signature' };
182
+ }
183
+
184
+ // Check authorization
185
+ const isAuthorized = await this.memberVerifier.isAuthorizedToJoin(strandId, key);
186
+ if (!isAuthorized) {
187
+ return { valid: false, reason: 'Not authorized to join strand' };
188
+ }
189
+
190
+ // Check if already registered
191
+ const alreadyRegistered = await this.memberRegistry.isMemberRegistered(strandId, key);
192
+ if (alreadyRegistered) {
193
+ return { valid: false, reason: 'Member already registered' };
194
+ }
195
+
196
+ return { valid: true };
197
+ }
198
+ }
199
+