@serfab/cadre-core 0.6.0 → 0.8.1

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 (166) hide show
  1. package/README.md +9 -8
  2. package/dist/authority-key.d.ts +41 -0
  3. package/dist/authority-key.js +52 -0
  4. package/dist/authority-key.js.map +1 -0
  5. package/dist/cadre-node.d.ts +777 -11
  6. package/dist/cadre-node.js +1912 -82
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/canonical-datetime.d.ts +33 -0
  9. package/dist/canonical-datetime.js +38 -0
  10. package/dist/canonical-datetime.js.map +1 -0
  11. package/dist/canonical-json.d.ts +12 -0
  12. package/dist/canonical-json.js +33 -0
  13. package/dist/canonical-json.js.map +1 -0
  14. package/dist/control-cohort.d.ts +63 -0
  15. package/dist/control-cohort.js +80 -0
  16. package/dist/control-cohort.js.map +1 -0
  17. package/dist/control-database.d.ts +259 -5
  18. package/dist/control-database.js +541 -128
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +89 -0
  21. package/dist/control-formation-recorder.js +139 -0
  22. package/dist/control-formation-recorder.js.map +1 -0
  23. package/dist/control-schema.d.ts +12 -0
  24. package/dist/control-schema.js +199 -0
  25. package/dist/control-schema.js.map +1 -0
  26. package/dist/control-stream.d.ts +54 -0
  27. package/dist/control-stream.js +104 -0
  28. package/dist/control-stream.js.map +1 -0
  29. package/dist/device-token.d.ts +50 -0
  30. package/dist/device-token.js +66 -0
  31. package/dist/device-token.js.map +1 -0
  32. package/dist/diagnostics/connection-path.d.ts +118 -0
  33. package/dist/diagnostics/connection-path.js +204 -0
  34. package/dist/diagnostics/connection-path.js.map +1 -0
  35. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  36. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  37. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  38. package/dist/hibernation-manager.d.ts +79 -0
  39. package/dist/hibernation-manager.js +173 -23
  40. package/dist/hibernation-manager.js.map +1 -1
  41. package/dist/index.d.ts +25 -4
  42. package/dist/index.js +59 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/key-store-file.d.ts +52 -0
  45. package/dist/key-store-file.js +194 -0
  46. package/dist/key-store-file.js.map +1 -0
  47. package/dist/key-store.d.ts +75 -0
  48. package/dist/key-store.js +66 -0
  49. package/dist/key-store.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +26 -0
  51. package/dist/peer-authorization.js +40 -0
  52. package/dist/peer-authorization.js.map +1 -0
  53. package/dist/peer-record.d.ts +89 -0
  54. package/dist/peer-record.js +117 -0
  55. package/dist/peer-record.js.map +1 -0
  56. package/dist/push-credentials.d.ts +34 -0
  57. package/dist/push-credentials.js +81 -0
  58. package/dist/push-credentials.js.map +1 -0
  59. package/dist/push-fanout.d.ts +137 -0
  60. package/dist/push-fanout.js +197 -0
  61. package/dist/push-fanout.js.map +1 -0
  62. package/dist/push-notifier-apns.d.ts +53 -0
  63. package/dist/push-notifier-apns.js +195 -0
  64. package/dist/push-notifier-apns.js.map +1 -0
  65. package/dist/push-notifier-fcm.d.ts +38 -0
  66. package/dist/push-notifier-fcm.js +183 -0
  67. package/dist/push-notifier-fcm.js.map +1 -0
  68. package/dist/push-notifier-shared.d.ts +18 -0
  69. package/dist/push-notifier-shared.js +25 -0
  70. package/dist/push-notifier-shared.js.map +1 -0
  71. package/dist/push-notifier.d.ts +71 -0
  72. package/dist/push-notifier.js +50 -0
  73. package/dist/push-notifier.js.map +1 -0
  74. package/dist/schema-verification.d.ts +11 -2
  75. package/dist/schema-verification.js +15 -4
  76. package/dist/schema-verification.js.map +1 -1
  77. package/dist/seed-bootstrap.d.ts +210 -7
  78. package/dist/seed-bootstrap.js +429 -131
  79. package/dist/seed-bootstrap.js.map +1 -1
  80. package/dist/seed-trust-policy.d.ts +63 -0
  81. package/dist/seed-trust-policy.js +56 -0
  82. package/dist/seed-trust-policy.js.map +1 -0
  83. package/dist/strand-addr-protocol.d.ts +132 -0
  84. package/dist/strand-addr-protocol.js +313 -0
  85. package/dist/strand-addr-protocol.js.map +1 -0
  86. package/dist/strand-cohort.d.ts +54 -0
  87. package/dist/strand-cohort.js +38 -0
  88. package/dist/strand-cohort.js.map +1 -0
  89. package/dist/strand-database.d.ts +54 -6
  90. package/dist/strand-database.js +88 -89
  91. package/dist/strand-database.js.map +1 -1
  92. package/dist/strand-formation-manager.d.ts +79 -19
  93. package/dist/strand-formation-manager.js +196 -104
  94. package/dist/strand-formation-manager.js.map +1 -1
  95. package/dist/strand-formation-protocol.d.ts +162 -0
  96. package/dist/strand-formation-protocol.js +279 -0
  97. package/dist/strand-formation-protocol.js.map +1 -0
  98. package/dist/strand-instance-manager.d.ts +73 -4
  99. package/dist/strand-instance-manager.js +167 -41
  100. package/dist/strand-instance-manager.js.map +1 -1
  101. package/dist/strand-member-key.d.ts +29 -0
  102. package/dist/strand-member-key.js +38 -0
  103. package/dist/strand-member-key.js.map +1 -0
  104. package/dist/strand-member-registry.d.ts +98 -0
  105. package/dist/strand-member-registry.js +129 -0
  106. package/dist/strand-member-registry.js.map +1 -0
  107. package/dist/strand-membership-writer.d.ts +361 -0
  108. package/dist/strand-membership-writer.js +449 -0
  109. package/dist/strand-membership-writer.js.map +1 -0
  110. package/dist/strand-solicitation.d.ts +77 -2
  111. package/dist/strand-solicitation.js +25 -4
  112. package/dist/strand-solicitation.js.map +1 -1
  113. package/dist/strand-wake-payload.d.ts +30 -0
  114. package/dist/strand-wake-payload.js +20 -0
  115. package/dist/strand-wake-payload.js.map +1 -0
  116. package/dist/strand-wake-protocol.d.ts +114 -0
  117. package/dist/strand-wake-protocol.js +257 -0
  118. package/dist/strand-wake-protocol.js.map +1 -0
  119. package/dist/strand-watcher.d.ts +6 -2
  120. package/dist/strand-watcher.js +57 -17
  121. package/dist/strand-watcher.js.map +1 -1
  122. package/dist/types.d.ts +413 -23
  123. package/dist/types.js +22 -5
  124. package/dist/types.js.map +1 -1
  125. package/package.json +14 -8
  126. package/src/authority-key.ts +68 -0
  127. package/src/cadre-node.ts +2937 -929
  128. package/src/canonical-datetime.ts +39 -0
  129. package/src/canonical-json.ts +30 -0
  130. package/src/control-cohort.ts +103 -0
  131. package/src/control-database.ts +931 -383
  132. package/src/control-formation-recorder.ts +151 -0
  133. package/src/control-schema.ts +198 -0
  134. package/src/control-stream.ts +128 -0
  135. package/src/device-token.ts +89 -0
  136. package/src/diagnostics/connection-path.ts +277 -0
  137. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  138. package/src/hibernation-manager.ts +197 -28
  139. package/src/index.ts +273 -79
  140. package/src/key-store-file.ts +203 -0
  141. package/src/key-store.ts +99 -0
  142. package/src/peer-authorization.ts +53 -0
  143. package/src/peer-record.ts +146 -0
  144. package/src/push-credentials.ts +84 -0
  145. package/src/push-fanout.ts +272 -0
  146. package/src/push-notifier-apns.ts +243 -0
  147. package/src/push-notifier-fcm.ts +221 -0
  148. package/src/push-notifier-shared.ts +28 -0
  149. package/src/push-notifier.ts +93 -0
  150. package/src/schema-verification.ts +18 -4
  151. package/src/seed-bootstrap.ts +504 -171
  152. package/src/seed-trust-policy.ts +107 -0
  153. package/src/strand-addr-protocol.ts +410 -0
  154. package/src/strand-cohort.ts +77 -0
  155. package/src/strand-database.ts +113 -126
  156. package/src/strand-formation-manager.ts +233 -142
  157. package/src/strand-formation-protocol.ts +391 -0
  158. package/src/strand-instance-manager.ts +207 -56
  159. package/src/strand-member-key.ts +39 -0
  160. package/src/strand-member-registry.ts +177 -0
  161. package/src/strand-membership-writer.ts +640 -0
  162. package/src/strand-solicitation.ts +93 -4
  163. package/src/strand-wake-payload.ts +32 -0
  164. package/src/strand-wake-protocol.ts +331 -0
  165. package/src/strand-watcher.ts +61 -17
  166. package/src/types.ts +1012 -575
package/dist/index.d.ts CHANGED
@@ -1,13 +1,34 @@
1
1
  export * from './types.js';
2
+ export { canonicalJson } from './canonical-json.js';
2
3
  export { CadreNode } from './cadre-node.js';
3
- export { ControlDatabase, type ControlDatabaseConfig } from './control-database.js';
4
+ export { ControlDatabase, buildAuthorizationMessage, type ControlDatabaseConfig, type ControlTable } from './control-database.js';
5
+ export { authorityKeyFromLibp2p, authorityPublicKeyFromPrivate, type AuthorityKeyPair } from './authority-key.js';
6
+ export { InMemoryKeyStore, KeyStoreAccessError, DEFAULT_IDENTITY_KEY_ID, type KeyStore, type KeyId } from './key-store.js';
4
7
  export { StrandDatabase, type StrandDatabaseConfig } from './strand-database.js';
5
8
  export { StrandWatcher, type StrandWatcherCallbacks, type StrandQueryable, type SAppIdLookup, type StrandRowWithApp } from './strand-watcher.js';
6
- export { StrandInstanceManager, type StartStrandConfig, getStrandStoragePath } from './strand-instance-manager.js';
9
+ export { StrandInstanceManager, type StartStrandConfig, type ResumeStrandOverrides, getStrandStoragePath } from './strand-instance-manager.js';
7
10
  export { HibernationManager, type HibernationCallbacks } from './hibernation-manager.js';
8
11
  export { ArachnodeStub, createArachnodeStub, type RingConfig } from './arachnode-stub.js';
9
12
  export { EnrollmentService, type MemberVerifier, type MemberRegistry } from './enrollment.js';
10
- export { StrandSolicitationService, type DisclosureValidator, type FormationUsageRecorder, type StrandProvisioner, type FormationSigner, type StrandSolicitationServiceOptions } from './strand-solicitation.js';
11
- export { SeedBootstrapService, SEED_PROTOCOL, type SeedBootstrapConfig, type SeedEventCallbacks } from './seed-bootstrap.js';
13
+ export { StrandSolicitationService, createDefaultFormationResponseValidator, type DisclosureValidator, type FormationUsageRecorder, type ResolvedHostStrand, type StrandProvisioner, type FormationSigner, type FormationResponseValidator, type StrandSolicitationServiceOptions } from './strand-solicitation.js';
14
+ export { ControlFormationUsageRecorder } from './control-formation-recorder.js';
15
+ export { generateStrandMemberKey, strandMemberKeyPair } from './strand-member-key.js';
16
+ export { signStrandPayload, verifyStrandPayload, bootstrapFounderMembership, issueInvite, consumeInvite, addMemberByAuthority, registerMemberPeer, addAuthority, removeAuthority, STRAND_ENGINE, STRAND_ENGINE_VERSION, type FounderBootstrapParams, type IssueInviteParams, type IssuedInvite, type ConsumeInviteParams, type AddMemberByAuthorityParams, type RegisterMemberPeerParams, type AddAuthorityParams, type RemoveAuthorityParams } from './strand-membership-writer.js';
17
+ export { canonicalDatetime } from './canonical-datetime.js';
18
+ export { StrandMemberRegistry, StrandMemberVerifier, memberRegistrationPayload, type StrandAdmission } from './strand-member-registry.js';
19
+ export { SeedBootstrapService, SEED_PROTOCOL, ed25519PublicKeyB64FromPeerId, type SeedBootstrapConfig, type SeedEventCallbacks } from './seed-bootstrap.js';
20
+ export { peerAuthorizationDigest, verifyPeerAuthorization } from './peer-authorization.js';
21
+ export { StrandWakeService, dialWake, WAKE_PROTOCOL, type StrandWakeServiceOptions, type DialWakeOptions } from './strand-wake-protocol.js';
22
+ export { StrandAddrService, collectStrandAddrs, STRAND_ADDR_PROTOCOL, type StrandAddrServiceOptions, type StrandAddrPeer, type CollectStrandAddrsOptions } from './strand-addr-protocol.js';
23
+ export { peerRecordSignedPayload, signPeerRecord, verifyPeerRecordSignature, isPeerRecordFresh, isSignalingAddr, orderSignalingFirst, currentMemberTrustPolicy, DEFAULT_PEER_RECORD_MAX_AGE_MS, DEFAULT_PEER_RECORD_HEARTBEAT_MS } from './peer-record.js';
24
+ export { deviceTokenSignedPayload, signDeviceTokenRecord, verifyDeviceTokenSignature, isPushPlatform } from './device-token.js';
25
+ export { STRAND_WAKE_TYPE, type StrandWakePayload } from './strand-wake-payload.js';
26
+ export type { PushNotifier, PushMessage, PushSendResult } from './push-notifier.js';
27
+ export { validatePushCredentials, redactPushCredentials, REDACTED } from './push-credentials.js';
28
+ export { PushFanoutService, DEFAULT_PUSH_COOLDOWN_MS, DEFAULT_PUSH_DEBOUNCE_MS, type PushFanoutOptions, type FanoutMember } from './push-fanout.js';
29
+ export { selectControlCohortDials, DEFAULT_CONTROL_COHORT_RECONCILE_MS, DEFAULT_CONTROL_COHORT_TARGET_DEGREE, type ControlCohortSelection } from './control-cohort.js';
30
+ export { dbAnchoredTrustPolicy, pinnedKeyTrustPolicy, tofuTrustPolicy, type SeedTrustPolicy, type SeedTrustContext, type SeedTrustDecision } from './seed-trust-policy.js';
12
31
  export { signSchema, verifySchema, assertSchemaSignature, SchemaVerificationError } from './schema-verification.js';
32
+ export { FormationListener, dialFormation, isValidResponderCreatesResult, FORMATION_PROTOCOL, type FormationParty, type FormationContactMessage, type FormationResultMessage, type FormationProvisionResult, type FormationStrandInfo, type FormationDbConnectionInfo, type FormationListenerOptions, type FormationDialOptions, type ResponderProvisionOutcome } from './strand-formation-protocol.js';
13
33
  export { StrandFormationManager, createStrandFormationManager, type StrandFormationManagerConfig, type StrandFormationManagerOptions } from './strand-formation-manager.js';
34
+ export { classifyTransport, classifyConnectionPath, summarizeConnectionPaths, emptyConnectionPathSummary, DEFAULT_SETTLE_WINDOW_MS, type ConnectionPathKind, type ConnectionTransport, type ConnectionPath, type ConnectionPathSummary, type ConnectionLike } from './diagnostics/connection-path.js';
package/dist/index.js CHANGED
@@ -1,9 +1,19 @@
1
1
  // Core types
2
2
  export * from './types.js';
3
+ // Canonical JSON serialization (shared signing payload format)
4
+ export { canonicalJson } from './canonical-json.js';
3
5
  // Main CadreNode class
4
6
  export { CadreNode } from './cadre-node.js';
5
7
  // Control database
6
- export { ControlDatabase } from './control-database.js';
8
+ export { ControlDatabase, buildAuthorizationMessage } from './control-database.js';
9
+ // Authority key bridge (libp2p Ed25519 -> base64url authority keypair)
10
+ export { authorityKeyFromLibp2p, authorityPublicKeyFromPrivate } from './authority-key.js';
11
+ // Pluggable key store (backend-agnostic identity/authority key material seam).
12
+ // Dependency-free: the interface, error, default slot id, and in-memory backend
13
+ // are safe in every (RN/browser/Node) entry graph. The Node FileKeyStore is a
14
+ // separate subpath module ('@serfab/cadre-core/key-store-file') so its node:fs
15
+ // import never lands here.
16
+ export { InMemoryKeyStore, KeyStoreAccessError, DEFAULT_IDENTITY_KEY_ID } from './key-store.js';
7
17
  // Strand database
8
18
  export { StrandDatabase } from './strand-database.js';
9
19
  // Strand management
@@ -16,11 +26,56 @@ export { ArachnodeStub, createArachnodeStub } from './arachnode-stub.js';
16
26
  // Enrollment
17
27
  export { EnrollmentService } from './enrollment.js';
18
28
  // Strand Solicitation
19
- export { StrandSolicitationService } from './strand-solicitation.js';
29
+ export { StrandSolicitationService, createDefaultFormationResponseValidator } from './strand-solicitation.js';
30
+ // DB-backed FormationUsageRecorder (reads/writes the real CadreControl tables)
31
+ export { ControlFormationUsageRecorder } from './control-formation-recorder.js';
32
+ // Closed-strand member key generation (ed25519 protobuf, base64) + the
33
+ // protobuf->base64url bridge that derives the founding Member/Authority key.
34
+ export { generateStrandMemberKey, strandMemberKeyPair } from './strand-member-key.js';
35
+ // Strand membership writer (founder bootstrap, invite issuance/consumption,
36
+ // authority-admit, member-peer registration, authority rotation, + shared signing
37
+ // primitives reused across the flows).
38
+ export { signStrandPayload, verifyStrandPayload, bootstrapFounderMembership, issueInvite, consumeInvite, addMemberByAuthority, registerMemberPeer, addAuthority, removeAuthority, STRAND_ENGINE, STRAND_ENGINE_VERSION } from './strand-membership-writer.js';
39
+ // Engine-canonical datetime helper (shared by control + strand signed-write flows
40
+ // so a signed timestamp byte-matches the datetime-coerced column the CHECK sees).
41
+ export { canonicalDatetime } from './canonical-datetime.js';
42
+ // Strand-DB-backed EnrollmentService backing: concrete MemberRegistry +
43
+ // MemberVerifier that write/read the real Strand.* membership tables.
44
+ export { StrandMemberRegistry, StrandMemberVerifier, memberRegistrationPayload } from './strand-member-registry.js';
20
45
  // Seed Bootstrap
21
- export { SeedBootstrapService, SEED_PROTOCOL } from './seed-bootstrap.js';
46
+ export { SeedBootstrapService, SEED_PROTOCOL, ed25519PublicKeyB64FromPeerId } from './seed-bootstrap.js';
47
+ // Peer Authorization (shared authority-signature digest + offline verifier)
48
+ export { peerAuthorizationDigest, verifyPeerAuthorization } from './peer-authorization.js';
49
+ // Strand Wake (control-network push-wake protocol)
50
+ export { StrandWakeService, dialWake, WAKE_PROTOCOL } from './strand-wake-protocol.js';
51
+ // Strand Address (control-network strand-address RPC) — wire types come via
52
+ // `export * from './types.js'` (StrandAddrRequest / StrandAddrResponse).
53
+ export { StrandAddrService, collectStrandAddrs, STRAND_ADDR_PROTOCOL } from './strand-addr-protocol.js';
54
+ // Peer-address record (self-published, signed, freshness-stamped CadrePeer row)
55
+ export { peerRecordSignedPayload, signPeerRecord, verifyPeerRecordSignature, isPeerRecordFresh, isSignalingAddr, orderSignalingFirst, currentMemberTrustPolicy, DEFAULT_PEER_RECORD_MAX_AGE_MS, DEFAULT_PEER_RECORD_HEARTBEAT_MS } from './peer-record.js';
56
+ // Device-token record (self-published, signed FCM/APNs push token — CadrePeer sibling)
57
+ export { deviceTokenSignedPayload, signDeviceTokenRecord, verifyDeviceTokenSignature, isPushPlatform } from './device-token.js';
58
+ // Strand-wake payload contract (canonical; shared by the server sender + RN receiver)
59
+ export { STRAND_WAKE_TYPE } from './strand-wake-payload.js';
60
+ // Push-credential validation + log redaction. Dependency-free (type-only imports),
61
+ // so a provisioner (cadre-host / cadre-provider) can reject a partial credential
62
+ // set and produce a key-safe log view without pulling the FCM/APNs sender graph.
63
+ export { validatePushCredentials, redactPushCredentials, REDACTED } from './push-credentials.js';
64
+ // Server-side push-wake trigger policy + fan-out (who/when to wake). Cross-platform
65
+ // clean — it imports only the PushNotifier *type*, so exporting it as a runtime
66
+ // value pulls no node:http2/node:crypto edge into the RN/browser graph.
67
+ export { PushFanoutService, DEFAULT_PUSH_COOLDOWN_MS, DEFAULT_PUSH_DEBOUNCE_MS } from './push-fanout.js';
68
+ // Control-cohort dial selection (backbone-preferential, bounded out-degree) +
69
+ // the cadence/degree defaults the proactive reconcile routine reads.
70
+ export { selectControlCohortDials, DEFAULT_CONTROL_COHORT_RECONCILE_MS, DEFAULT_CONTROL_COHORT_TARGET_DEGREE } from './control-cohort.js';
71
+ // Seed trust policy (trust anchor for incoming seeds)
72
+ export { dbAnchoredTrustPolicy, pinnedKeyTrustPolicy, tofuTrustPolicy } from './seed-trust-policy.js';
22
73
  // Schema Verification
23
74
  export { signSchema, verifySchema, assertSchemaSignature, SchemaVerificationError } from './schema-verification.js';
24
- // Strand Formation (strand-proto integration)
75
+ // Strand Formation transport (native cadre-core protocol)
76
+ export { FormationListener, dialFormation, isValidResponderCreatesResult, FORMATION_PROTOCOL } from './strand-formation-protocol.js';
77
+ // Strand Formation manager (drives the native transport)
25
78
  export { StrandFormationManager, createStrandFormationManager } from './strand-formation-manager.js';
79
+ // Connection-path diagnostics (relayed vs direct classification + summary)
80
+ export { classifyTransport, classifyConnectionPath, summarizeConnectionPaths, emptyConnectionPathSummary, DEFAULT_SETTLE_WINDOW_MS } from './diagnostics/connection-path.js';
26
81
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,cAAc,YAAY,CAAC;AAE3B,uBAAuB;AACvB,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,mBAAmB;AACnB,OAAO,EAAE,eAAe,EAA8B,MAAM,uBAAuB,CAAC;AAEpF,kBAAkB;AAClB,OAAO,EAAE,cAAc,EAA6B,MAAM,sBAAsB,CAAC;AAEjF,oBAAoB;AACpB,OAAO,EACL,aAAa,EAKd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,qBAAqB,EAErB,oBAAoB,EACrB,MAAM,8BAA8B,CAAC;AAEtC,cAAc;AACd,OAAO,EACL,kBAAkB,EAEnB,MAAM,0BAA0B,CAAC;AAElC,mBAAmB;AACnB,OAAO,EACL,aAAa,EACb,mBAAmB,EAEpB,MAAM,qBAAqB,CAAC;AAE7B,aAAa;AACb,OAAO,EACL,iBAAiB,EAGlB,MAAM,iBAAiB,CAAC;AAEzB,sBAAsB;AACtB,OAAO,EACL,yBAAyB,EAM1B,MAAM,0BAA0B,CAAC;AAElC,iBAAiB;AACjB,OAAO,EACL,oBAAoB,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,qBAAqB,EACrB,0BAA0B,EAC1B,cAAc,EACf,MAAM,mBAAmB,CAAC;AAE3B,sFAAsF;AACtF,OAAO,EAAE,gBAAgB,EAA0B,MAAM,0BAA0B,CAAC;AAWpF,mFAAmF;AACnF,iFAAiF;AACjF,iFAAiF;AACjF,OAAO,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjG,oFAAoF;AACpF,gFAAgF;AAChF,wEAAwE;AACxE,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,wBAAwB,EAGzB,MAAM,kBAAkB,CAAC;AAE1B,8EAA8E;AAC9E,qEAAqE;AACrE,OAAO,EACL,wBAAwB,EACxB,mCAAmC,EACnC,oCAAoC,EAErC,MAAM,qBAAqB,CAAC;AAE7B,sDAAsD;AACtD,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,eAAe,EAIhB,MAAM,wBAAwB,CAAC;AAEhC,sBAAsB;AACtB,OAAO,EACL,UAAU,EACV,YAAY,EACZ,qBAAqB,EACrB,uBAAuB,EACxB,MAAM,0BAA0B,CAAC;AAElC,0DAA0D;AAC1D,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,6BAA6B,EAC7B,kBAAkB,EAUnB,MAAM,gCAAgC,CAAC;AAExC,yDAAyD;AACzD,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAG7B,MAAM,+BAA+B,CAAC;AAEvC,2EAA2E;AAC3E,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,0BAA0B,EAC1B,wBAAwB,EAMzB,MAAM,kCAAkC,CAAC"}
@@ -0,0 +1,52 @@
1
+ import type { KeyId, KeyStore } from './key-store.js';
2
+ /**
3
+ * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
4
+ * containing the raw material bytes. The directory is created lazily on first
5
+ * {@link set}. Suitable for headless Node cadre nodes and tests; for mobile use
6
+ * a platform secure-enclave backend instead.
7
+ */
8
+ export declare class FileKeyStore implements KeyStore {
9
+ private readonly dir;
10
+ constructor(dir: string);
11
+ private slotPath;
12
+ /**
13
+ * Sibling path for the temp file written before the atomic rename. The random
14
+ * component makes concurrent {@link set}s to the same slot (and crash-orphaned
15
+ * leftovers) collide-free; it lives in the same directory as the slot so the
16
+ * final {@link rename} stays within one filesystem and is therefore atomic.
17
+ */
18
+ private tempPath;
19
+ get(keyId: KeyId): Promise<Uint8Array | undefined>;
20
+ /**
21
+ * Crash-atomic write: a concurrent reader sees either the complete previous
22
+ * bytes or the complete new bytes, never a torn slot. The new material is
23
+ * written to a sibling temp file, fsync'd, then atomically renamed over the
24
+ * slot. A failure at any point removes the temp file and leaves the previous
25
+ * slot untouched.
26
+ */
27
+ set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void>;
28
+ /**
29
+ * Write material to `tmpPath`, durably land it, then atomically swap it onto
30
+ * `finalPath`.
31
+ *
32
+ * Durability bar: the temp file is fsync'd before the rename so a power loss
33
+ * cannot surface a slot whose bytes never reached the platter, and the slot
34
+ * directory is fsync'd afterwards (best-effort — see {@link syncDir}) so the
35
+ * rename itself survives a crash. On POSIX `rename(2)` replaces atomically;
36
+ * Node maps to `MoveFileEx(MOVEFILE_REPLACE_EXISTING)` on Windows, which is
37
+ * also atomic — though it can fail with `EPERM`/`EBUSY` if another process
38
+ * holds the destination open. That cross-process case is out of scope here
39
+ * (the in-process identity path is single-flight); such a failure surfaces
40
+ * to the caller with the previous slot left intact.
41
+ */
42
+ private writeSlotAtomically;
43
+ /**
44
+ * Best-effort fsync of the slot directory so a fresh slot's directory entry is
45
+ * durable across power loss. Opening a directory for fsync is not portable
46
+ * (unsupported on Windows and some filesystems), and rename atomicity does not
47
+ * depend on it — so a failure here is logged and swallowed, never surfaced.
48
+ */
49
+ private syncDir;
50
+ delete(keyId: KeyId): Promise<void>;
51
+ list(): Promise<KeyId[]>;
52
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Node-only file-backed {@link KeyStore}: one file per slot under a configured
3
+ * directory, holding the raw key material bytes.
4
+ *
5
+ * This module imports `node:fs/promises`, `node:path`, and `node:crypto`, so it
6
+ * is deliberately kept OUT of the package's cross-platform default entry
7
+ * (`./index.js`). Import it from the dedicated subpath instead:
8
+ *
9
+ * ```ts
10
+ * import { FileKeyStore } from '@serfab/cadre-core/key-store-file';
11
+ * ```
12
+ *
13
+ * A React Native / browser entry graph never resolves this path, so the
14
+ * `node:fs` edge never reaches a bundler that cannot satisfy it.
15
+ */
16
+ import debug from 'debug';
17
+ import { mkdir, readFile, rm, readdir, rename, open } from 'node:fs/promises';
18
+ import { join } from 'node:path';
19
+ import { randomBytes } from 'node:crypto';
20
+ import { KeyStoreAccessError } from './key-store.js';
21
+ const log = debug('sereus:cadre:key-store-file');
22
+ /** Suffix appended to the encoded keyId to form a slot filename. */
23
+ const SLOT_SUFFIX = '.key';
24
+ /**
25
+ * Suffix for the transient file written then atomically renamed over the slot.
26
+ * Distinct from {@link SLOT_SUFFIX}, so {@link FileKeyStore.list} (which matches
27
+ * only `.key`) never surfaces an in-flight or crash-orphaned temp file.
28
+ */
29
+ const TEMP_SUFFIX = '.tmp';
30
+ /** Best-effort POSIX permissions (ignored on Windows / unsupported FSes). */
31
+ const DIR_MODE = 0o700;
32
+ const FILE_MODE = 0o600;
33
+ /**
34
+ * Percent-encode a keyId into a filesystem-safe filename component. Beyond
35
+ * `encodeURIComponent` (which already escapes `/`, spaces, and unicode), this
36
+ * also escapes the unreserved characters `encodeURIComponent` leaves intact but
37
+ * that are unsafe in filenames on some platforms (notably `*` on Windows) — and
38
+ * `.` so the `.key` suffix is the only literal dot, making suffix-stripping in
39
+ * {@link decodeKeyId} unambiguous. {@link decodeKeyId} reverses every escape via
40
+ * `decodeURIComponent`. The result contains only `A-Za-z0-9-_` and `%XX`.
41
+ */
42
+ function encodeKeyId(keyId) {
43
+ return encodeURIComponent(keyId).replace(/[!'()*~.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
44
+ }
45
+ /**
46
+ * Reverse {@link encodeKeyId}: strip the slot suffix and percent-decode. Returns
47
+ * `undefined` for a `.key` filename this store did not write (a foreign file
48
+ * with an invalid percent-sequence), so {@link FileKeyStore.list} can skip it
49
+ * rather than letting one undecodable entry throw and break enumeration of every
50
+ * real slot.
51
+ */
52
+ function decodeKeyId(fileName) {
53
+ const encoded = fileName.slice(0, -SLOT_SUFFIX.length);
54
+ try {
55
+ return decodeURIComponent(encoded);
56
+ }
57
+ catch (error) {
58
+ log('FileKeyStore: skipping undecodable slot filename %s: %o', fileName, error);
59
+ return undefined;
60
+ }
61
+ }
62
+ /** Whether an unknown error is a Node "file/dir not found" (ENOENT). */
63
+ function isNotFound(error) {
64
+ return typeof error === 'object' && error !== null
65
+ && error.code === 'ENOENT';
66
+ }
67
+ /**
68
+ * File-backed {@link KeyStore}. Each slot is `<dir>/<encoded keyId>.key`
69
+ * containing the raw material bytes. The directory is created lazily on first
70
+ * {@link set}. Suitable for headless Node cadre nodes and tests; for mobile use
71
+ * a platform secure-enclave backend instead.
72
+ */
73
+ export class FileKeyStore {
74
+ constructor(dir) {
75
+ this.dir = dir;
76
+ }
77
+ slotPath(keyId) {
78
+ return join(this.dir, `${encodeKeyId(keyId)}${SLOT_SUFFIX}`);
79
+ }
80
+ /**
81
+ * Sibling path for the temp file written before the atomic rename. The random
82
+ * component makes concurrent {@link set}s to the same slot (and crash-orphaned
83
+ * leftovers) collide-free; it lives in the same directory as the slot so the
84
+ * final {@link rename} stays within one filesystem and is therefore atomic.
85
+ */
86
+ tempPath(keyId) {
87
+ const unique = randomBytes(6).toString('hex');
88
+ return join(this.dir, `${encodeKeyId(keyId)}.${unique}${TEMP_SUFFIX}`);
89
+ }
90
+ async get(keyId) {
91
+ try {
92
+ const buf = await readFile(this.slotPath(keyId));
93
+ // Copy into a plain Uint8Array decoupled from Node's Buffer pool.
94
+ return new Uint8Array(buf);
95
+ }
96
+ catch (error) {
97
+ // A missing slot is "empty" (undefined), NOT an error — so a
98
+ // load-or-create caller generates a key rather than mistaking a
99
+ // permission failure for absence. Any other failure (e.g. EACCES) is
100
+ // surfaced as access-denied so callers do not clobber an existing key.
101
+ if (isNotFound(error))
102
+ return undefined;
103
+ throw new KeyStoreAccessError(keyId, `FileKeyStore: failed to read key slot ${keyId}`, { cause: error });
104
+ }
105
+ }
106
+ /**
107
+ * Crash-atomic write: a concurrent reader sees either the complete previous
108
+ * bytes or the complete new bytes, never a torn slot. The new material is
109
+ * written to a sibling temp file, fsync'd, then atomically renamed over the
110
+ * slot. A failure at any point removes the temp file and leaves the previous
111
+ * slot untouched.
112
+ */
113
+ async set(keyId, keyMaterial) {
114
+ await mkdir(this.dir, { recursive: true, mode: DIR_MODE });
115
+ await this.writeSlotAtomically(this.tempPath(keyId), this.slotPath(keyId), keyMaterial);
116
+ }
117
+ /**
118
+ * Write material to `tmpPath`, durably land it, then atomically swap it onto
119
+ * `finalPath`.
120
+ *
121
+ * Durability bar: the temp file is fsync'd before the rename so a power loss
122
+ * cannot surface a slot whose bytes never reached the platter, and the slot
123
+ * directory is fsync'd afterwards (best-effort — see {@link syncDir}) so the
124
+ * rename itself survives a crash. On POSIX `rename(2)` replaces atomically;
125
+ * Node maps to `MoveFileEx(MOVEFILE_REPLACE_EXISTING)` on Windows, which is
126
+ * also atomic — though it can fail with `EPERM`/`EBUSY` if another process
127
+ * holds the destination open. That cross-process case is out of scope here
128
+ * (the in-process identity path is single-flight); such a failure surfaces
129
+ * to the caller with the previous slot left intact.
130
+ */
131
+ async writeSlotAtomically(tmpPath, finalPath, keyMaterial) {
132
+ // 'wx' creates the temp file exclusively; a name collision (astronomically
133
+ // unlikely given the random component) fails here before we own anything.
134
+ const handle = await open(tmpPath, 'wx', FILE_MODE);
135
+ try {
136
+ try {
137
+ await handle.writeFile(keyMaterial);
138
+ await handle.sync(); // land bytes on disk before the rename exposes them
139
+ }
140
+ finally {
141
+ await handle.close().catch(() => { });
142
+ }
143
+ await rename(tmpPath, finalPath);
144
+ }
145
+ catch (error) {
146
+ // Any failure after creation (write, sync, or rename): drop the temp
147
+ // file so a retry leaves no `.tmp` debris. The slot is only ever
148
+ // swapped by the atomic rename, so the previous bytes stay intact.
149
+ await rm(tmpPath, { force: true }).catch(() => { });
150
+ throw error;
151
+ }
152
+ await this.syncDir();
153
+ }
154
+ /**
155
+ * Best-effort fsync of the slot directory so a fresh slot's directory entry is
156
+ * durable across power loss. Opening a directory for fsync is not portable
157
+ * (unsupported on Windows and some filesystems), and rename atomicity does not
158
+ * depend on it — so a failure here is logged and swallowed, never surfaced.
159
+ */
160
+ async syncDir() {
161
+ let dirHandle;
162
+ try {
163
+ dirHandle = await open(this.dir, 'r');
164
+ await dirHandle.sync();
165
+ }
166
+ catch (error) {
167
+ log('FileKeyStore: directory fsync skipped for %s: %o', this.dir, error);
168
+ }
169
+ finally {
170
+ await dirHandle?.close().catch(() => { });
171
+ }
172
+ }
173
+ async delete(keyId) {
174
+ // force:true makes removing an absent slot a no-op (idempotent).
175
+ await rm(this.slotPath(keyId), { force: true });
176
+ }
177
+ async list() {
178
+ let entries;
179
+ try {
180
+ entries = await readdir(this.dir);
181
+ }
182
+ catch (error) {
183
+ // An absent directory means no slots yet — not a failure.
184
+ if (isNotFound(error))
185
+ return [];
186
+ throw new Error('FileKeyStore: failed to list key directory', { cause: error });
187
+ }
188
+ return entries
189
+ .filter((name) => name.endsWith(SLOT_SUFFIX))
190
+ .map(decodeKeyId)
191
+ .filter((id) => id !== undefined);
192
+ }
193
+ }
194
+ //# sourceMappingURL=key-store-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key-store-file.js","sourceRoot":"","sources":["../src/key-store-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;A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,CAAC;QAC1E,CAAC;gBAAS,CAAC;YACV,MAAM,SAAS,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC1C,CAAC;IACF,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,KAAY;QACxB,iEAAiE;QACjE,MAAM,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,IAAI;QACT,IAAI,OAAiB,CAAC;QACtB,IAAI,CAAC;YACJ,OAAO,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACnC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,0DAA0D;YAC1D,IAAI,UAAU,CAAC,KAAK,CAAC;gBAAE,OAAO,EAAE,CAAC;YACjC,MAAM,IAAI,KAAK,CAAC,4CAA4C,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACjF,CAAC;QACD,OAAO,OAAO;aACZ,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;aAC5C,GAAG,CAAC,WAAW,CAAC;aAChB,MAAM,CAAC,CAAC,EAAE,EAAe,EAAE,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC;IACjD,CAAC;CACD"}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Backend-agnostic store for raw private key material.
3
+ *
4
+ * Mobile cadre nodes hold sensitive key material at rest: the libp2p
5
+ * peer/node identity key and (in the single-key reference model) the authority
6
+ * signing key derived from it. This module defines the seam those keys flow
7
+ * through so a platform-secure backend (iOS Keychain / Android Keystore) can be
8
+ * plugged in without `@serfab/cadre-core` taking any platform dependency.
9
+ *
10
+ * This file is dependency-free (no node:/RN imports) so it is safe in every
11
+ * entry graph. The Node reference {@link FileKeyStore} lives in a separate
12
+ * subpath module (`./key-store-file.js`) so its `node:fs` import never lands in
13
+ * the cross-platform default entry.
14
+ */
15
+ /** Opaque identifier for a stored key slot (e.g. 'cadre/identity'). */
16
+ export type KeyId = string;
17
+ /**
18
+ * Default slot id for the node identity key. `CadreNode` reads/persists its
19
+ * libp2p identity here when a {@link KeyStore} is configured without an explicit
20
+ * `identityKeyId`.
21
+ */
22
+ export declare const DEFAULT_IDENTITY_KEY_ID: KeyId;
23
+ /**
24
+ * Backend-agnostic store for raw private key material. Implementations may be
25
+ * file-based, OS-keyring, or platform secure-enclave backed (iOS Keychain /
26
+ * Android Keystore). The interface makes no assumption about the backend and
27
+ * never logs, returns, or throws key material.
28
+ *
29
+ * Key material is raw bytes (e.g. libp2p protobuf-serialized private keys).
30
+ * Text-only backends encode/decode (base64) internally; byte-native backends
31
+ * (LevelDB) store as-is.
32
+ */
33
+ export interface KeyStore {
34
+ /** Resolves to the stored material, or undefined if the slot is empty. */
35
+ get(keyId: KeyId): Promise<Uint8Array | undefined>;
36
+ /** Writes/overwrites the slot. */
37
+ set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void>;
38
+ /** Removes the slot. Idempotent — succeeds even if absent. */
39
+ delete(keyId: KeyId): Promise<void>;
40
+ /** Enumerates the keyIds this store knows about. */
41
+ list(): Promise<KeyId[]>;
42
+ }
43
+ /**
44
+ * Thrown by {@link KeyStore.get} when access was denied or could not be
45
+ * satisfied (e.g. a biometric/device-unlock prompt was cancelled or failed).
46
+ * Distinguishes "access refused" from "slot empty" (which is a plain `undefined`
47
+ * return). Biometric gating itself is out of scope here, but `get` rejecting
48
+ * with this error is the contract a gated backend uses, so callers must not
49
+ * treat it as "no key" (which would trigger key regeneration and silent
50
+ * identity loss).
51
+ *
52
+ * Carries only the {@link keyId} — never key material — so it is safe to log.
53
+ */
54
+ export declare class KeyStoreAccessError extends Error {
55
+ readonly keyId: KeyId;
56
+ constructor(keyId: KeyId, message: string, options?: {
57
+ cause?: unknown;
58
+ });
59
+ }
60
+ /**
61
+ * In-memory {@link KeyStore} backed by a `Map`. For tests and ephemeral nodes;
62
+ * nothing is persisted across process restarts. Dependency-free, so it is safe
63
+ * in every entry graph.
64
+ *
65
+ * Material is defensively copied on both {@link set} and {@link get} so a caller
66
+ * mutating its own buffer cannot alter stored state (and vice versa), matching
67
+ * the fresh-buffer semantics a file/keyring backend produces.
68
+ */
69
+ export declare class InMemoryKeyStore implements KeyStore {
70
+ private readonly slots;
71
+ get(keyId: KeyId): Promise<Uint8Array | undefined>;
72
+ set(keyId: KeyId, keyMaterial: Uint8Array): Promise<void>;
73
+ delete(keyId: KeyId): Promise<void>;
74
+ list(): Promise<KeyId[]>;
75
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Backend-agnostic store for raw private key material.
3
+ *
4
+ * Mobile cadre nodes hold sensitive key material at rest: the libp2p
5
+ * peer/node identity key and (in the single-key reference model) the authority
6
+ * signing key derived from it. This module defines the seam those keys flow
7
+ * through so a platform-secure backend (iOS Keychain / Android Keystore) can be
8
+ * plugged in without `@serfab/cadre-core` taking any platform dependency.
9
+ *
10
+ * This file is dependency-free (no node:/RN imports) so it is safe in every
11
+ * entry graph. The Node reference {@link FileKeyStore} lives in a separate
12
+ * subpath module (`./key-store-file.js`) so its `node:fs` import never lands in
13
+ * the cross-platform default entry.
14
+ */
15
+ /**
16
+ * Default slot id for the node identity key. `CadreNode` reads/persists its
17
+ * libp2p identity here when a {@link KeyStore} is configured without an explicit
18
+ * `identityKeyId`.
19
+ */
20
+ export const DEFAULT_IDENTITY_KEY_ID = 'cadre/identity';
21
+ /**
22
+ * Thrown by {@link KeyStore.get} when access was denied or could not be
23
+ * satisfied (e.g. a biometric/device-unlock prompt was cancelled or failed).
24
+ * Distinguishes "access refused" from "slot empty" (which is a plain `undefined`
25
+ * return). Biometric gating itself is out of scope here, but `get` rejecting
26
+ * with this error is the contract a gated backend uses, so callers must not
27
+ * treat it as "no key" (which would trigger key regeneration and silent
28
+ * identity loss).
29
+ *
30
+ * Carries only the {@link keyId} — never key material — so it is safe to log.
31
+ */
32
+ export class KeyStoreAccessError extends Error {
33
+ constructor(keyId, message, options) {
34
+ super(message, options);
35
+ this.name = 'KeyStoreAccessError';
36
+ this.keyId = keyId;
37
+ }
38
+ }
39
+ /**
40
+ * In-memory {@link KeyStore} backed by a `Map`. For tests and ephemeral nodes;
41
+ * nothing is persisted across process restarts. Dependency-free, so it is safe
42
+ * in every entry graph.
43
+ *
44
+ * Material is defensively copied on both {@link set} and {@link get} so a caller
45
+ * mutating its own buffer cannot alter stored state (and vice versa), matching
46
+ * the fresh-buffer semantics a file/keyring backend produces.
47
+ */
48
+ export class InMemoryKeyStore {
49
+ constructor() {
50
+ this.slots = new Map();
51
+ }
52
+ async get(keyId) {
53
+ const stored = this.slots.get(keyId);
54
+ return stored ? stored.slice() : undefined;
55
+ }
56
+ async set(keyId, keyMaterial) {
57
+ this.slots.set(keyId, keyMaterial.slice());
58
+ }
59
+ async delete(keyId) {
60
+ this.slots.delete(keyId);
61
+ }
62
+ async list() {
63
+ return [...this.slots.keys()];
64
+ }
65
+ }
66
+ //# sourceMappingURL=key-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key-store.js","sourceRoot":"","sources":["../src/key-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAKH;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAU,gBAAgB,CAAC;AA0B/D;;;;;;;;;;GAUG;AACH,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAG7C,YAAY,KAAY,EAAE,OAAe,EAAE,OAA6B;QACvE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;QAClC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACpB,CAAC;CACD;AAED;;;;;;;;GAQG;AACH,MAAM,OAAO,gBAAgB;IAA7B;QACkB,UAAK,GAAG,IAAI,GAAG,EAAqB,CAAC;IAkBvD,CAAC;IAhBA,KAAK,CAAC,GAAG,CAAC,KAAY;QACrB,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACrC,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5C,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,KAAY,EAAE,WAAuB;QAC9C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,KAAY;QACxB,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,IAAI;QACT,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAC/B,CAAC;CACD"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Canonical digest an authority signs to authorize a peer.
3
+ *
4
+ * This is the exact byte construction {@link SeedBootstrapService.authorizePeer}
5
+ * signs over when it inserts an authorized `CadrePeer` row:
6
+ * `digest([peerId], 'sha256', 'base64url')`. Factored into one place so the
7
+ * producer (authority signing) and the verifier (the offline `cadre enroll
8
+ * register` check) can never drift apart — change the digest here and both move
9
+ * together. The SQL mirror is the bare single-field `digest(coalesce(new.PeerId, old.PeerId))`.
10
+ */
11
+ export declare function peerAuthorizationDigest(peerId: string): string;
12
+ /**
13
+ * Verify that `signature` is a valid authority ed25519 signature over `peerId`'s
14
+ * authorization digest, using `authorityPublicKey` (base64url).
15
+ *
16
+ * This is the mirror of the signing done in
17
+ * {@link SeedBootstrapService.authorizePeer}: it checks the signature against
18
+ * {@link peerAuthorizationDigest}. A `true` result means the holder of the
19
+ * authority private key vouched for this peer ID — it does NOT mean the peer is
20
+ * registered anywhere.
21
+ *
22
+ * Returns a boolean and never throws: malformed base64url, a bad/garbage key, or
23
+ * any crypto failure resolves to `false` (callers want a verdict, not an
24
+ * exception). The catch is logged at debug.
25
+ */
26
+ export declare function verifyPeerAuthorization(peerId: string, authorityPublicKey: string, signature: string): boolean;
@@ -0,0 +1,40 @@
1
+ import debug from 'debug';
2
+ import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
+ const log = debug('sereus:cadre:peer-authorization');
4
+ /**
5
+ * Canonical digest an authority signs to authorize a peer.
6
+ *
7
+ * This is the exact byte construction {@link SeedBootstrapService.authorizePeer}
8
+ * signs over when it inserts an authorized `CadrePeer` row:
9
+ * `digest([peerId], 'sha256', 'base64url')`. Factored into one place so the
10
+ * producer (authority signing) and the verifier (the offline `cadre enroll
11
+ * register` check) can never drift apart — change the digest here and both move
12
+ * together. The SQL mirror is the bare single-field `digest(coalesce(new.PeerId, old.PeerId))`.
13
+ */
14
+ export function peerAuthorizationDigest(peerId) {
15
+ return digest([peerId], 'sha256', 'base64url');
16
+ }
17
+ /**
18
+ * Verify that `signature` is a valid authority ed25519 signature over `peerId`'s
19
+ * authorization digest, using `authorityPublicKey` (base64url).
20
+ *
21
+ * This is the mirror of the signing done in
22
+ * {@link SeedBootstrapService.authorizePeer}: it checks the signature against
23
+ * {@link peerAuthorizationDigest}. A `true` result means the holder of the
24
+ * authority private key vouched for this peer ID — it does NOT mean the peer is
25
+ * registered anywhere.
26
+ *
27
+ * Returns a boolean and never throws: malformed base64url, a bad/garbage key, or
28
+ * any crypto failure resolves to `false` (callers want a verdict, not an
29
+ * exception). The catch is logged at debug.
30
+ */
31
+ export function verifyPeerAuthorization(peerId, authorityPublicKey, signature) {
32
+ try {
33
+ return verify(peerAuthorizationDigest(peerId), signature, authorityPublicKey, 'ed25519', 'base64url', 'base64url', 'base64url');
34
+ }
35
+ catch (error) {
36
+ log('verifyPeerAuthorization failed: %o', error);
37
+ return false;
38
+ }
39
+ }
40
+ //# sourceMappingURL=peer-authorization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peer-authorization.js","sourceRoot":"","sources":["../src/peer-authorization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAEnE,MAAM,GAAG,GAAG,KAAK,CAAC,iCAAiC,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB,CAAC,MAAc;IACpD,OAAO,MAAM,CAAC,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,WAAW,CAAW,CAAC;AAC3D,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAAc,EACd,kBAA0B,EAC1B,SAAiB;IAEjB,IAAI,CAAC;QACH,OAAO,MAAM,CACX,uBAAuB,CAAC,MAAM,CAAC,EAC/B,SAAS,EACT,kBAAkB,EAClB,SAAS,EACT,WAAW,EACX,WAAW,EACX,WAAW,CACZ,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAC;QACjD,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}