@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,164 +1,164 @@
1
- /**
2
- * Peer-address record helpers: the single source of truth for the bytes a node
3
- * signs when publishing its own `CadrePeer` row and re-verifies when resolving
4
- * another peer's row.
5
- *
6
- * The signed payload is a single SHA-256 digest over the shared domain-tagged
7
- * field vector (see control-authorization.ts) — the crypto plugin's injective
8
- * multi-field encoding, so no field split is ambiguous. It is intentionally NOT
9
- * JSON-canonicalized (deterministic across node/browser/RN, no key ordering)
10
- * and — crucially — is reconstructable inside the `CadrePeer.AuthorizedUpdate`
11
- * SQL constraint from the row's own columns:
12
- *
13
- * digest('CadreControl.CadrePeer', 'publish',
14
- * new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text))
15
- *
16
- * Keep {@link peerRecordSignedPayload} and that constraint byte-for-byte in
17
- * sync. The `'publish'` action tag marks this as a peer's SELF-signed record
18
- * (signed with the peer's own key, not an owner key) and keeps it disjoint from
19
- * every owner-signed digest.
20
- *
21
- * `publicKey` is deliberately excluded from the payload — it is the key the
22
- * signature is verified *with* (so a signature already commits to exactly one
23
- * key), and its binding to `peerId` is checked separately at resolve time.
24
- */
25
-
26
- import type { Multiaddr } from '@multiformats/multiaddr';
27
- import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
28
- import { controlAuthorizationFields } from './control-authorization.js';
29
- import type { PeerAddressRecord, PeerResolveTrustPolicy } from './types.js';
30
-
31
- /**
32
- * Default freshness ceiling for resolved peer-address records (15 minutes).
33
- * A record older than this is treated as stale and filtered out, so a resolver
34
- * never hands back a dead relay reservation. The publish path re-stamps at
35
- * roughly half this interval (see {@link DEFAULT_PEER_RECORD_HEARTBEAT_MS}).
36
- */
37
- export const DEFAULT_PEER_RECORD_MAX_AGE_MS = 15 * 60 * 1000;
38
-
39
- /**
40
- * TTL heartbeat interval for re-publishing the self record — half the freshness
41
- * ceiling, so a record is refreshed well before it can go stale.
42
- */
43
- export const DEFAULT_PEER_RECORD_HEARTBEAT_MS = DEFAULT_PEER_RECORD_MAX_AGE_MS / 2;
44
-
45
- /** The signaling/relay prefix a WebRTC (or any relayed) dial path consumes. */
46
- const SIGNALING_PREFIX = '/p2p-circuit';
47
-
48
- /**
49
- * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
50
- * `CadrePeer.AuthorizedUpdate` constraint exactly; both sides take the default
51
- * base64url output of a single `digest(...)`, which round-trips cleanly (unlike
52
- * concatenating several base64url digests).
53
- *
54
- * @param peerId - base58btc libp2p peer id (the row key)
55
- * @param multiaddr - the comma-joined `Multiaddr` string EXACTLY as stored
56
- * @param updatedAt - epoch-ms freshness stamp
57
- */
58
- export function peerRecordSignedPayload(peerId: string, multiaddr: string, updatedAt: number): string {
59
- const fields = controlAuthorizationFields('CadreControl.CadrePeer', 'publish', [peerId, multiaddr, String(updatedAt)]);
60
- return digest(fields, 'sha256', 'base64url') as string;
61
- }
62
-
63
- /**
64
- * Sign a peer-address record with the ed25519 private key behind its `peerId`.
65
- * Returns a fully-populated {@link PeerAddressRecord} (the `addrs` order is
66
- * preserved and is the order signed over).
67
- *
68
- * @param fields - the record fields to sign (signaling addr first by convention)
69
- * @param privateKeyB64 - base64url ed25519 seed (see `ed25519KeyPairFromLibp2p`)
70
- */
71
- export function signPeerRecord(
72
- fields: { peerId: string; publicKey: string; addrs: string[]; updatedAt: number },
73
- privateKeyB64: string
74
- ): PeerAddressRecord {
75
- const payloadDigest = peerRecordSignedPayload(fields.peerId, fields.addrs.join(','), fields.updatedAt);
76
- const sig = sign(
77
- payloadDigest,
78
- privateKeyB64,
79
- 'ed25519',
80
- 'base64url',
81
- 'base64url',
82
- 'base64url'
83
- ) as string;
84
- return { peerId: fields.peerId, publicKey: fields.publicKey, addrs: [...fields.addrs], updatedAt: fields.updatedAt, sig };
85
- }
86
-
87
- /**
88
- * Verify a record's self-signature against its own `publicKey`. Reconstructs the
89
- * signed bytes from the record exactly as {@link signPeerRecord} produced them.
90
- * Returns false on a missing key/sig or any verification failure.
91
- */
92
- export function verifyPeerRecordSignature(record: PeerAddressRecord): boolean {
93
- if (!record.publicKey || !record.sig) {
94
- return false;
95
- }
96
- const payloadDigest = peerRecordSignedPayload(record.peerId, record.addrs.join(','), record.updatedAt);
97
- return verify(
98
- payloadDigest,
99
- record.sig,
100
- record.publicKey,
101
- 'ed25519',
102
- 'base64url',
103
- 'base64url',
104
- 'base64url'
105
- );
106
- }
107
-
108
- /**
109
- * Freshness predicate: true when `updatedAt` is a positive stamp within
110
- * `maxAgeMs` of `now`. A non-positive `updatedAt` (never self-published) is
111
- * never fresh.
112
- */
113
- export function isPeerRecordFresh(updatedAt: number, maxAgeMs: number, now: number): boolean {
114
- if (!(updatedAt > 0)) {
115
- return false;
116
- }
117
- return now - updatedAt <= maxAgeMs;
118
- }
119
-
120
- /** True if `addr` is a `/p2p-circuit` signaling/relay multiaddr. */
121
- export function isSignalingAddr(addr: string): boolean {
122
- return addr.includes(SIGNALING_PREFIX);
123
- }
124
-
125
- /**
126
- * The peer id a multiaddr terminates in, or `null` when it names none.
127
- *
128
- * The LAST `/p2p/` component is the dial target: a circuit address
129
- * (`…/p2p/<relay>/p2p-circuit/p2p/<target>`) names the relay first and the peer
130
- * being reached last. Replaces the deprecated `Multiaddr.getPeerId()`, which
131
- * cannot express that distinction.
132
- */
133
- export function trailingPeerId(addr: Multiaddr): string | null {
134
- const p2p = addr.getComponents().filter((c) => c.name === 'p2p');
135
- return p2p.length > 0 ? (p2p[p2p.length - 1].value ?? null) : null;
136
- }
137
-
138
- /**
139
- * Return `addrs` with signaling (`/p2p-circuit`) addrs first, otherwise stable.
140
- * Used to present the WebRTC dial input ahead of direct addrs. Does NOT mutate
141
- * the input and must not be used before signature verification (verification
142
- * uses the original on-record order).
143
- */
144
- export function orderSignalingFirst(addrs: string[]): string[] {
145
- const signaling = addrs.filter(isSignalingAddr);
146
- const rest = addrs.filter(a => !isSignalingAddr(a));
147
- return [...signaling, ...rest];
148
- }
149
-
150
- /**
151
- * Default resolve trust gate: trust any peer that has a `CadrePeer` row.
152
- *
153
- * A row only exists because an owner signed its `AuthorizedInsert`, so row
154
- * presence already means "owner-vouched member". This is the seam where a
155
- * stricter policy (trust circle, pinned keys) plugs in — see
156
- * {@link PeerResolveTrustPolicy}.
157
- */
158
- export function currentMemberTrustPolicy(): PeerResolveTrustPolicy {
159
- return {
160
- evaluate() {
161
- return true;
162
- },
163
- };
164
- }
1
+ /**
2
+ * Peer-address record helpers: the single source of truth for the bytes a node
3
+ * signs when publishing its own `CadrePeer` row and re-verifies when resolving
4
+ * another peer's row.
5
+ *
6
+ * The signed payload is a single SHA-256 digest over the shared domain-tagged
7
+ * field vector (see control-authorization.ts) — the crypto plugin's injective
8
+ * multi-field encoding, so no field split is ambiguous. It is intentionally NOT
9
+ * JSON-canonicalized (deterministic across node/browser/RN, no key ordering)
10
+ * and — crucially — is reconstructable inside the `CadrePeer.AuthorizedUpdate`
11
+ * SQL constraint from the row's own columns:
12
+ *
13
+ * digest('CadreControl.CadrePeer', 'publish',
14
+ * new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text))
15
+ *
16
+ * Keep {@link peerRecordSignedPayload} and that constraint byte-for-byte in
17
+ * sync. The `'publish'` action tag marks this as a peer's SELF-signed record
18
+ * (signed with the peer's own key, not an owner key) and keeps it disjoint from
19
+ * every owner-signed digest.
20
+ *
21
+ * `publicKey` is deliberately excluded from the payload — it is the key the
22
+ * signature is verified *with* (so a signature already commits to exactly one
23
+ * key), and its binding to `peerId` is checked separately at resolve time.
24
+ */
25
+
26
+ import type { Multiaddr } from '@multiformats/multiaddr';
27
+ import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
28
+ import { controlAuthorizationFields } from './control-authorization.js';
29
+ import type { PeerAddressRecord, PeerResolveTrustPolicy } from './types.js';
30
+
31
+ /**
32
+ * Default freshness ceiling for resolved peer-address records (15 minutes).
33
+ * A record older than this is treated as stale and filtered out, so a resolver
34
+ * never hands back a dead relay reservation. The publish path re-stamps at
35
+ * roughly half this interval (see {@link DEFAULT_PEER_RECORD_HEARTBEAT_MS}).
36
+ */
37
+ export const DEFAULT_PEER_RECORD_MAX_AGE_MS = 15 * 60 * 1000;
38
+
39
+ /**
40
+ * TTL heartbeat interval for re-publishing the self record — half the freshness
41
+ * ceiling, so a record is refreshed well before it can go stale.
42
+ */
43
+ export const DEFAULT_PEER_RECORD_HEARTBEAT_MS = DEFAULT_PEER_RECORD_MAX_AGE_MS / 2;
44
+
45
+ /** The signaling/relay prefix a WebRTC (or any relayed) dial path consumes. */
46
+ const SIGNALING_PREFIX = '/p2p-circuit';
47
+
48
+ /**
49
+ * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
50
+ * `CadrePeer.AuthorizedUpdate` constraint exactly; both sides take the default
51
+ * base64url output of a single `digest(...)`, which round-trips cleanly (unlike
52
+ * concatenating several base64url digests).
53
+ *
54
+ * @param peerId - base58btc libp2p peer id (the row key)
55
+ * @param multiaddr - the comma-joined `Multiaddr` string EXACTLY as stored
56
+ * @param updatedAt - epoch-ms freshness stamp
57
+ */
58
+ export function peerRecordSignedPayload(peerId: string, multiaddr: string, updatedAt: number): string {
59
+ const fields = controlAuthorizationFields('CadreControl.CadrePeer', 'publish', [peerId, multiaddr, String(updatedAt)]);
60
+ return digest(fields, 'sha256', 'base64url') as string;
61
+ }
62
+
63
+ /**
64
+ * Sign a peer-address record with the ed25519 private key behind its `peerId`.
65
+ * Returns a fully-populated {@link PeerAddressRecord} (the `addrs` order is
66
+ * preserved and is the order signed over).
67
+ *
68
+ * @param fields - the record fields to sign (signaling addr first by convention)
69
+ * @param privateKeyB64 - base64url ed25519 seed (see `ed25519KeyPairFromLibp2p`)
70
+ */
71
+ export function signPeerRecord(
72
+ fields: { peerId: string; publicKey: string; addrs: string[]; updatedAt: number },
73
+ privateKeyB64: string
74
+ ): PeerAddressRecord {
75
+ const payloadDigest = peerRecordSignedPayload(fields.peerId, fields.addrs.join(','), fields.updatedAt);
76
+ const sig = sign(
77
+ payloadDigest,
78
+ privateKeyB64,
79
+ 'ed25519',
80
+ 'base64url',
81
+ 'base64url',
82
+ 'base64url'
83
+ ) as string;
84
+ return { peerId: fields.peerId, publicKey: fields.publicKey, addrs: [...fields.addrs], updatedAt: fields.updatedAt, sig };
85
+ }
86
+
87
+ /**
88
+ * Verify a record's self-signature against its own `publicKey`. Reconstructs the
89
+ * signed bytes from the record exactly as {@link signPeerRecord} produced them.
90
+ * Returns false on a missing key/sig or any verification failure.
91
+ */
92
+ export function verifyPeerRecordSignature(record: PeerAddressRecord): boolean {
93
+ if (!record.publicKey || !record.sig) {
94
+ return false;
95
+ }
96
+ const payloadDigest = peerRecordSignedPayload(record.peerId, record.addrs.join(','), record.updatedAt);
97
+ return verify(
98
+ payloadDigest,
99
+ record.sig,
100
+ record.publicKey,
101
+ 'ed25519',
102
+ 'base64url',
103
+ 'base64url',
104
+ 'base64url'
105
+ );
106
+ }
107
+
108
+ /**
109
+ * Freshness predicate: true when `updatedAt` is a positive stamp within
110
+ * `maxAgeMs` of `now`. A non-positive `updatedAt` (never self-published) is
111
+ * never fresh.
112
+ */
113
+ export function isPeerRecordFresh(updatedAt: number, maxAgeMs: number, now: number): boolean {
114
+ if (!(updatedAt > 0)) {
115
+ return false;
116
+ }
117
+ return now - updatedAt <= maxAgeMs;
118
+ }
119
+
120
+ /** True if `addr` is a `/p2p-circuit` signaling/relay multiaddr. */
121
+ export function isSignalingAddr(addr: string): boolean {
122
+ return addr.includes(SIGNALING_PREFIX);
123
+ }
124
+
125
+ /**
126
+ * The peer id a multiaddr terminates in, or `null` when it names none.
127
+ *
128
+ * The LAST `/p2p/` component is the dial target: a circuit address
129
+ * (`…/p2p/<relay>/p2p-circuit/p2p/<target>`) names the relay first and the peer
130
+ * being reached last. Replaces the deprecated `Multiaddr.getPeerId()`, which
131
+ * cannot express that distinction.
132
+ */
133
+ export function trailingPeerId(addr: Multiaddr): string | null {
134
+ const p2p = addr.getComponents().filter((c) => c.name === 'p2p');
135
+ return p2p.length > 0 ? (p2p[p2p.length - 1].value ?? null) : null;
136
+ }
137
+
138
+ /**
139
+ * Return `addrs` with signaling (`/p2p-circuit`) addrs first, otherwise stable.
140
+ * Used to present the WebRTC dial input ahead of direct addrs. Does NOT mutate
141
+ * the input and must not be used before signature verification (verification
142
+ * uses the original on-record order).
143
+ */
144
+ export function orderSignalingFirst(addrs: string[]): string[] {
145
+ const signaling = addrs.filter(isSignalingAddr);
146
+ const rest = addrs.filter(a => !isSignalingAddr(a));
147
+ return [...signaling, ...rest];
148
+ }
149
+
150
+ /**
151
+ * Default resolve trust gate: trust any peer that has a `CadrePeer` row.
152
+ *
153
+ * A row only exists because an owner signed its `AuthorizedInsert`, so row
154
+ * presence already means "owner-vouched member". This is the seam where a
155
+ * stricter policy (trust circle, pinned keys) plugs in — see
156
+ * {@link PeerResolveTrustPolicy}.
157
+ */
158
+ export function currentMemberTrustPolicy(): PeerResolveTrustPolicy {
159
+ return {
160
+ evaluate() {
161
+ return true;
162
+ },
163
+ };
164
+ }
@@ -1,84 +1,84 @@
1
- /**
2
- * push-credentials.ts — pure validation + log-redaction for {@link PushCredentials}.
3
- *
4
- * The platform-push credentials a deployment provisions (`cadre-host` from its
5
- * secret store, `cadre-provider` from per-tenant config) are written into a
6
- * spawned node's config under `CadreNodeConfig.push`. This module is the
7
- * dependency-free seam those provisioners share to (a) reject a *partial* set
8
- * before it reaches a node — a present platform block must carry all its required
9
- * fields, or it fails fast at provisioning rather than at first push — and (b)
10
- * produce a log-safe view that never leaks a private key.
11
- *
12
- * It imports only the *types* (erased at emit), so it pulls no node:crypto /
13
- * node:http2 edge — a provisioner can import these functions without dragging in
14
- * the FCM/APNs senders.
15
- */
16
-
17
- import type { PushCredentials, FcmCredentials, ApnsCredentials } from './types.js';
18
-
19
- /** Marker substituted for every secret field by {@link redactPushCredentials}. */
20
- export const REDACTED = '[redacted]';
21
-
22
- /**
23
- * Validate a resolved push-credential bundle, returning human-readable errors
24
- * (empty ⇒ valid). Each platform block is optional, but a *present* block must
25
- * carry every required field — a partial set (e.g. APNs `keyId` without
26
- * `privateKey`) is a misconfiguration that must surface at provisioning time, not
27
- * silently at the first wake. A bundle with neither platform is valid (push is
28
- * opt-in); callers that require at least one platform check that separately.
29
- */
30
- export function validatePushCredentials(push: PushCredentials): string[] {
31
- const errors: string[] = [];
32
- if (push.fcm) errors.push(...validateFcm(push.fcm));
33
- if (push.apns) errors.push(...validateApns(push.apns));
34
- return errors;
35
- }
36
-
37
- function validateFcm(fcm: FcmCredentials): string[] {
38
- return missingFields('fcm', fcm as unknown as Record<string, unknown>, [
39
- 'projectId',
40
- 'clientEmail',
41
- 'privateKey',
42
- ]);
43
- }
44
-
45
- function validateApns(apns: ApnsCredentials): string[] {
46
- return missingFields('apns', apns as unknown as Record<string, unknown>, [
47
- 'keyId',
48
- 'teamId',
49
- 'bundleId',
50
- 'privateKey',
51
- ]);
52
- }
53
-
54
- /** Names the required fields of `platform` that are missing or blank. */
55
- function missingFields(platform: string, obj: Record<string, unknown>, required: string[]): string[] {
56
- return required
57
- .filter((f) => typeof obj[f] !== 'string' || (obj[f] as string).trim().length === 0)
58
- .map((f) => `push.${platform}.${f} is required when a ${platform} credential block is present`);
59
- }
60
-
61
- /**
62
- * Return a log-safe shallow copy of a push bundle with every private key replaced
63
- * by {@link REDACTED}. Use this for ANY debug/log line that touches push config —
64
- * `privateKey` fields are secrets and must never reach a log sink (the same rule
65
- * the startup/seed tokens follow).
66
- */
67
- export function redactPushCredentials(push: PushCredentials): Record<string, unknown> {
68
- const out: Record<string, unknown> = {};
69
- if (push.fcm) {
70
- out.fcm = { projectId: push.fcm.projectId, clientEmail: push.fcm.clientEmail, privateKey: REDACTED };
71
- }
72
- if (push.apns) {
73
- out.apns = {
74
- keyId: push.apns.keyId,
75
- teamId: push.apns.teamId,
76
- bundleId: push.apns.bundleId,
77
- ...(push.apns.production !== undefined ? { production: push.apns.production } : {}),
78
- privateKey: REDACTED,
79
- };
80
- }
81
- if (push.cooldownMs !== undefined) out.cooldownMs = push.cooldownMs;
82
- if (push.debounceMs !== undefined) out.debounceMs = push.debounceMs;
83
- return out;
84
- }
1
+ /**
2
+ * push-credentials.ts — pure validation + log-redaction for {@link PushCredentials}.
3
+ *
4
+ * The platform-push credentials a deployment provisions (`cadre-host` from its
5
+ * secret store, `cadre-provider` from per-tenant config) are written into a
6
+ * spawned node's config under `CadreNodeConfig.push`. This module is the
7
+ * dependency-free seam those provisioners share to (a) reject a *partial* set
8
+ * before it reaches a node — a present platform block must carry all its required
9
+ * fields, or it fails fast at provisioning rather than at first push — and (b)
10
+ * produce a log-safe view that never leaks a private key.
11
+ *
12
+ * It imports only the *types* (erased at emit), so it pulls no node:crypto /
13
+ * node:http2 edge — a provisioner can import these functions without dragging in
14
+ * the FCM/APNs senders.
15
+ */
16
+
17
+ import type { PushCredentials, FcmCredentials, ApnsCredentials } from './types.js';
18
+
19
+ /** Marker substituted for every secret field by {@link redactPushCredentials}. */
20
+ export const REDACTED = '[redacted]';
21
+
22
+ /**
23
+ * Validate a resolved push-credential bundle, returning human-readable errors
24
+ * (empty ⇒ valid). Each platform block is optional, but a *present* block must
25
+ * carry every required field — a partial set (e.g. APNs `keyId` without
26
+ * `privateKey`) is a misconfiguration that must surface at provisioning time, not
27
+ * silently at the first wake. A bundle with neither platform is valid (push is
28
+ * opt-in); callers that require at least one platform check that separately.
29
+ */
30
+ export function validatePushCredentials(push: PushCredentials): string[] {
31
+ const errors: string[] = [];
32
+ if (push.fcm) errors.push(...validateFcm(push.fcm));
33
+ if (push.apns) errors.push(...validateApns(push.apns));
34
+ return errors;
35
+ }
36
+
37
+ function validateFcm(fcm: FcmCredentials): string[] {
38
+ return missingFields('fcm', fcm as unknown as Record<string, unknown>, [
39
+ 'projectId',
40
+ 'clientEmail',
41
+ 'privateKey',
42
+ ]);
43
+ }
44
+
45
+ function validateApns(apns: ApnsCredentials): string[] {
46
+ return missingFields('apns', apns as unknown as Record<string, unknown>, [
47
+ 'keyId',
48
+ 'teamId',
49
+ 'bundleId',
50
+ 'privateKey',
51
+ ]);
52
+ }
53
+
54
+ /** Names the required fields of `platform` that are missing or blank. */
55
+ function missingFields(platform: string, obj: Record<string, unknown>, required: string[]): string[] {
56
+ return required
57
+ .filter((f) => typeof obj[f] !== 'string' || (obj[f] as string).trim().length === 0)
58
+ .map((f) => `push.${platform}.${f} is required when a ${platform} credential block is present`);
59
+ }
60
+
61
+ /**
62
+ * Return a log-safe shallow copy of a push bundle with every private key replaced
63
+ * by {@link REDACTED}. Use this for ANY debug/log line that touches push config —
64
+ * `privateKey` fields are secrets and must never reach a log sink (the same rule
65
+ * the startup/seed tokens follow).
66
+ */
67
+ export function redactPushCredentials(push: PushCredentials): Record<string, unknown> {
68
+ const out: Record<string, unknown> = {};
69
+ if (push.fcm) {
70
+ out.fcm = { projectId: push.fcm.projectId, clientEmail: push.fcm.clientEmail, privateKey: REDACTED };
71
+ }
72
+ if (push.apns) {
73
+ out.apns = {
74
+ keyId: push.apns.keyId,
75
+ teamId: push.apns.teamId,
76
+ bundleId: push.apns.bundleId,
77
+ ...(push.apns.production !== undefined ? { production: push.apns.production } : {}),
78
+ privateKey: REDACTED,
79
+ };
80
+ }
81
+ if (push.cooldownMs !== undefined) out.cooldownMs = push.cooldownMs;
82
+ if (push.debounceMs !== undefined) out.debounceMs = push.debounceMs;
83
+ return out;
84
+ }
package/src/push-node.ts CHANGED
@@ -1,64 +1,64 @@
1
- /**
2
- * push-node.ts — Node-only subpath entry for platform push **construction**.
3
- *
4
- * Import from the dedicated subpath, never the package root:
5
- *
6
- * ```ts
7
- * import { createPushNotifier } from '@serfab/cadre-core/push-node';
8
- * ```
9
- *
10
- * The FCM/APNs implementations reach for `node:crypto` / `node:http2`, so they
11
- * are quarantined here — unreachable from the cross-platform `./index.js` graph
12
- * (same isolation pattern as `./key-store-file`). A React Native / browser entry
13
- * never resolves this path, so the Node builtins never reach a bundler that
14
- * cannot satisfy them. The core references only the {@link PushNotifier}
15
- * *interface* (`push-notifier.ts`) and a Node host injects the instance built
16
- * here into `CadreNodeConfig.push.notifier`.
17
- */
18
-
19
- import type { PushCredentials, PushPlatform } from './types.js';
20
- import type { PushMessage, PushNotifier, PushSendResult } from './push-notifier.js';
21
- import { createFcmPushNotifier, type FcmPushDeps } from './push-notifier-fcm.js';
22
- import { createApnsPushNotifier, type ApnsPushDeps } from './push-notifier-apns.js';
23
-
24
- /**
25
- * Per-platform transport/clock/log seams, injected by tests. Defaults are the
26
- * real implementations (global `fetch` for FCM, a `node:http2` session for APNs).
27
- */
28
- export interface PushNotifierDeps {
29
- fcm?: FcmPushDeps;
30
- apns?: ApnsPushDeps;
31
- }
32
-
33
- /**
34
- * Build a {@link PushNotifier} router over the configured credentials. Only the
35
- * platforms whose credentials are present get a backing implementation; a `send`
36
- * for an unconfigured platform returns a best-effort `no <platform> credentials`
37
- * failure rather than throwing.
38
- */
39
- export function createPushNotifier(creds: PushCredentials, deps: PushNotifierDeps = {}): PushNotifier {
40
- const fcm = creds.fcm ? createFcmPushNotifier(creds.fcm, deps.fcm) : undefined;
41
- const apns = creds.apns ? createApnsPushNotifier(creds.apns, deps.apns) : undefined;
42
-
43
- async function send(msg: PushMessage): Promise<PushSendResult> {
44
- if (msg.platform === 'fcm') return fcm ? fcm.send(msg) : noCreds('fcm');
45
- if (msg.platform === 'apns') return apns ? apns.send(msg) : noCreds('apns');
46
- return { ok: false, unregistered: false, error: `unknown platform ${String(msg.platform)}` };
47
- }
48
-
49
- async function close(): Promise<void> {
50
- await Promise.all([fcm?.close(), apns?.close()]);
51
- }
52
-
53
- return { send, close };
54
- }
55
-
56
- /** Best-effort no-op result for a platform with no configured credentials. */
57
- function noCreds(platform: PushPlatform): PushSendResult {
58
- return { ok: false, unregistered: false, error: `no ${platform} credentials` };
59
- }
60
-
61
- // Per-platform builders + their injected-dep types, for a host that wants a
62
- // single-platform notifier or to inject a fake transport directly.
63
- export { createFcmPushNotifier, createApnsPushNotifier };
64
- export type { FcmPushDeps, ApnsPushDeps };
1
+ /**
2
+ * push-node.ts — Node-only subpath entry for platform push **construction**.
3
+ *
4
+ * Import from the dedicated subpath, never the package root:
5
+ *
6
+ * ```ts
7
+ * import { createPushNotifier } from '@serfab/cadre-core/push-node';
8
+ * ```
9
+ *
10
+ * The FCM/APNs implementations reach for `node:crypto` / `node:http2`, so they
11
+ * are quarantined here — unreachable from the cross-platform `./index.js` graph
12
+ * (same isolation pattern as `./key-store-file`). A React Native / browser entry
13
+ * never resolves this path, so the Node builtins never reach a bundler that
14
+ * cannot satisfy them. The core references only the {@link PushNotifier}
15
+ * *interface* (`push-notifier.ts`) and a Node host injects the instance built
16
+ * here into `CadreNodeConfig.push.notifier`.
17
+ */
18
+
19
+ import type { PushCredentials, PushPlatform } from './types.js';
20
+ import type { PushMessage, PushNotifier, PushSendResult } from './push-notifier.js';
21
+ import { createFcmPushNotifier, type FcmPushDeps } from './push-notifier-fcm.js';
22
+ import { createApnsPushNotifier, type ApnsPushDeps } from './push-notifier-apns.js';
23
+
24
+ /**
25
+ * Per-platform transport/clock/log seams, injected by tests. Defaults are the
26
+ * real implementations (global `fetch` for FCM, a `node:http2` session for APNs).
27
+ */
28
+ export interface PushNotifierDeps {
29
+ fcm?: FcmPushDeps;
30
+ apns?: ApnsPushDeps;
31
+ }
32
+
33
+ /**
34
+ * Build a {@link PushNotifier} router over the configured credentials. Only the
35
+ * platforms whose credentials are present get a backing implementation; a `send`
36
+ * for an unconfigured platform returns a best-effort `no <platform> credentials`
37
+ * failure rather than throwing.
38
+ */
39
+ export function createPushNotifier(creds: PushCredentials, deps: PushNotifierDeps = {}): PushNotifier {
40
+ const fcm = creds.fcm ? createFcmPushNotifier(creds.fcm, deps.fcm) : undefined;
41
+ const apns = creds.apns ? createApnsPushNotifier(creds.apns, deps.apns) : undefined;
42
+
43
+ async function send(msg: PushMessage): Promise<PushSendResult> {
44
+ if (msg.platform === 'fcm') return fcm ? fcm.send(msg) : noCreds('fcm');
45
+ if (msg.platform === 'apns') return apns ? apns.send(msg) : noCreds('apns');
46
+ return { ok: false, unregistered: false, error: `unknown platform ${String(msg.platform)}` };
47
+ }
48
+
49
+ async function close(): Promise<void> {
50
+ await Promise.all([fcm?.close(), apns?.close()]);
51
+ }
52
+
53
+ return { send, close };
54
+ }
55
+
56
+ /** Best-effort no-op result for a platform with no configured credentials. */
57
+ function noCreds(platform: PushPlatform): PushSendResult {
58
+ return { ok: false, unregistered: false, error: `no ${platform} credentials` };
59
+ }
60
+
61
+ // Per-platform builders + their injected-dep types, for a host that wants a
62
+ // single-platform notifier or to inject a fake transport directly.
63
+ export { createFcmPushNotifier, createApnsPushNotifier };
64
+ export type { FcmPushDeps, ApnsPushDeps };