@serfab/cadre-core 0.7.1 → 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 +770 -11
  6. package/dist/cadre-node.js +1900 -88
  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 +197 -9
  78. package/dist/seed-bootstrap.js +396 -137
  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 -100
  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 +406 -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 -948
  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 +464 -188
  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 -141
  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 -582
@@ -0,0 +1,221 @@
1
+ /**
2
+ * push-notifier-fcm.ts — FCM HTTP v1 strand-wake delivery.
3
+ *
4
+ * Server-only: mints a Google OAuth2 access token (RS256 JWT bearer grant signed
5
+ * with `node:crypto`) and POSTs a data message to the FCM v1 endpoint. The legacy
6
+ * server-key `fcm.googleapis.com/fcm/send` API is deprecated, so we use HTTP v1.
7
+ *
8
+ * The network call is behind an injected `fetch`-like seam so unit tests assert
9
+ * the request shape and map every documented response code with no real network
10
+ * and no credentials. Failures are returned as {@link PushSendResult} values.
11
+ *
12
+ * Secret hygiene: the service-account `privateKey`, the minted JWT, and full
13
+ * device tokens are never logged — failure log lines carry only a status/error
14
+ * code and a redacted token prefix.
15
+ */
16
+
17
+ // Namespace import (not `import { sign }`): this module is server-only and is
18
+ // reached only via the guarded dynamic import in CadreNode, but bundlers still
19
+ // analyse that lazy chunk. A *named* import of `node:crypto` hard-fails the
20
+ // browser build ("sign is not exported by __vite-browser-external"), whereas a
21
+ // namespace import of the deliberately-unaliased external only warns (matching
22
+ // the `node:http2` namespace import in push-notifier-apns.ts). The browser
23
+ // never executes this code (config.push is node-only), so the warning is benign.
24
+ import * as nodeCrypto from 'node:crypto';
25
+ import debug from 'debug';
26
+ import type { FcmCredentials } from './types.js';
27
+ import type { PushMessage, PushNotifier, PushSendResult } from './push-notifier.js';
28
+ import { MAX_REASON_LEN, b64urlJson, errText, redact } from './push-notifier-shared.js';
29
+
30
+ const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
31
+ const FCM_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
32
+ const JWT_BEARER_GRANT = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
33
+ /** Re-mint the access token this many ms before its stated expiry. */
34
+ const TOKEN_REFRESH_SKEW_MS = 60_000;
35
+ /** OAuth2 access tokens are short-lived (≤1h); assume 1h when unstated. */
36
+ const DEFAULT_TOKEN_TTL_MS = 3_600_000;
37
+
38
+ const debugFcm = debug('sereus:cadre:push:fcm');
39
+
40
+ /** Minimal `fetch` Response shape the FCM sender consumes. */
41
+ export interface FcmResponseLike {
42
+ status: number;
43
+ json(): Promise<unknown>;
44
+ text(): Promise<string>;
45
+ }
46
+
47
+ /** Injected `fetch`-like transport (default: global `fetch`). */
48
+ export type FcmFetch = (
49
+ url: string,
50
+ init: { method: string; headers: Record<string, string>; body: string }
51
+ ) => Promise<FcmResponseLike>;
52
+
53
+ export interface FcmPushDeps {
54
+ /** Network transport. Defaults to global `fetch`. */
55
+ fetch?: FcmFetch;
56
+ /** Monotonic clock (ms). Defaults to `Date.now`. Injected for cache tests. */
57
+ now?: () => number;
58
+ /** Failure log seam (default: `debug('sereus:cadre:push:fcm')`). */
59
+ log?: (line: string) => void;
60
+ }
61
+
62
+ /** A cached OAuth2 access token and the wall-clock ms after which to re-mint. */
63
+ interface CachedAccessToken {
64
+ value: string;
65
+ expiresAt: number;
66
+ }
67
+
68
+ export function createFcmPushNotifier(creds: FcmCredentials, deps: FcmPushDeps = {}): PushNotifier {
69
+ const doFetch: FcmFetch = deps.fetch ?? ((url, init) => fetch(url, init));
70
+ const now = deps.now ?? (() => Date.now());
71
+ const log = deps.log ?? ((line: string) => debugFcm(line));
72
+ const sendUrl = `https://fcm.googleapis.com/v1/projects/${creds.projectId}/messages:send`;
73
+
74
+ let cached: CachedAccessToken | null = null;
75
+
76
+ async function send(msg: PushMessage): Promise<PushSendResult> {
77
+ let token: string;
78
+ try {
79
+ token = await accessToken(false);
80
+ } catch (err) {
81
+ log(`oauth mint failed: ${errText(err)}`);
82
+ return { ok: false, unregistered: false, error: `fcm oauth mint failed: ${errText(err)}` };
83
+ }
84
+
85
+ const first = await postSend(msg, token);
86
+ if (first.status !== 401) return mapResult(first, msg.token);
87
+
88
+ // The cached access token was rejected (expired/revoked mid-flight). Re-mint
89
+ // once and retry the single send; a second failure is returned as-is.
90
+ let retryToken: string;
91
+ try {
92
+ retryToken = await accessToken(true);
93
+ } catch (err) {
94
+ log(`oauth re-mint failed: ${errText(err)}`);
95
+ return { ok: false, unregistered: false, error: `fcm oauth re-mint failed: ${errText(err)}` };
96
+ }
97
+ return mapResult(await postSend(msg, retryToken), msg.token);
98
+ }
99
+
100
+ async function postSend(msg: PushMessage, token: string): Promise<{ status: number; body: string }> {
101
+ const body = JSON.stringify({
102
+ message: {
103
+ token: msg.token,
104
+ data: {
105
+ type: msg.payload.type,
106
+ strandId: msg.payload.strandId,
107
+ reason: msg.payload.reason.slice(0, MAX_REASON_LEN),
108
+ },
109
+ android: { priority: 'high' },
110
+ },
111
+ });
112
+ const res = await doFetch(sendUrl, {
113
+ method: 'POST',
114
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
115
+ body,
116
+ });
117
+ return { status: res.status, body: await safeText(res) };
118
+ }
119
+
120
+ function mapResult(res: { status: number; body: string }, deviceToken: string): PushSendResult {
121
+ if (res.status === 200) return { ok: true };
122
+ const summary = errorSummary(res.status, res.body);
123
+ if (isUnregistered(res.status, res.body)) {
124
+ log(`unregistered token=${redact(deviceToken)} (${summary})`);
125
+ return { ok: false, unregistered: true, error: summary };
126
+ }
127
+ log(`send failed token=${redact(deviceToken)} (${summary})`);
128
+ return { ok: false, unregistered: false, error: summary };
129
+ }
130
+
131
+ async function accessToken(forceRefresh: boolean): Promise<string> {
132
+ if (!forceRefresh && cached && cached.expiresAt > now()) return cached.value;
133
+ cached = null;
134
+ const minted = await mintAccessToken();
135
+ cached = { value: minted.value, expiresAt: now() + minted.ttlMs - TOKEN_REFRESH_SKEW_MS };
136
+ return minted.value;
137
+ }
138
+
139
+ async function mintAccessToken(): Promise<{ value: string; ttlMs: number }> {
140
+ const jwt = signOauthJwt();
141
+ const res = await doFetch(TOKEN_ENDPOINT, {
142
+ method: 'POST',
143
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
144
+ body: `grant_type=${encodeURIComponent(JWT_BEARER_GRANT)}&assertion=${encodeURIComponent(jwt)}`,
145
+ });
146
+ if (res.status !== 200) {
147
+ throw new Error(`token endpoint ${res.status}: ${await safeText(res)}`);
148
+ }
149
+ const parsed = (await res.json()) as { access_token?: unknown; expires_in?: unknown };
150
+ if (typeof parsed.access_token !== 'string') {
151
+ throw new Error('token endpoint returned no access_token');
152
+ }
153
+ const ttlMs = typeof parsed.expires_in === 'number' ? parsed.expires_in * 1000 : DEFAULT_TOKEN_TTL_MS;
154
+ return { value: parsed.access_token, ttlMs };
155
+ }
156
+
157
+ function signOauthJwt(): string {
158
+ const iat = Math.floor(now() / 1000);
159
+ const header = { alg: 'RS256', typ: 'JWT' };
160
+ const claims = {
161
+ iss: creds.clientEmail,
162
+ sub: creds.clientEmail,
163
+ scope: FCM_SCOPE,
164
+ aud: TOKEN_ENDPOINT,
165
+ iat,
166
+ exp: iat + 3600,
167
+ };
168
+ const signingInput = `${b64urlJson(header)}.${b64urlJson(claims)}`;
169
+ const sig = nodeCrypto.sign('RSA-SHA256', Buffer.from(signingInput), creds.privateKey).toString('base64url');
170
+ return `${signingInput}.${sig}`;
171
+ }
172
+
173
+ async function close(): Promise<void> {
174
+ cached = null;
175
+ }
176
+
177
+ return { send, close };
178
+ }
179
+
180
+ /**
181
+ * Whether an FCM v1 error response names a permanently-invalid registration
182
+ * token: a 404 (`UNREGISTERED`), or a 400 `INVALID_ARGUMENT` whose message names
183
+ * the registration token. A generic 400 (malformed message) is NOT unregistered.
184
+ */
185
+ function isUnregistered(status: number, body: string): boolean {
186
+ if (status === 404) return true;
187
+ if (status !== 400) return false;
188
+ const code = fcmErrorCode(body);
189
+ if (code === 'UNREGISTERED') return true;
190
+ if (code === 'INVALID_ARGUMENT' && /registration[ -]token|not a valid fcm registration/i.test(body)) return true;
191
+ return false;
192
+ }
193
+
194
+ /** Pull the FCM `errorCode` (FcmError detail) or RPC `status` out of the body. */
195
+ function fcmErrorCode(body: string): string | null {
196
+ try {
197
+ const parsed = JSON.parse(body) as {
198
+ error?: { status?: string; details?: Array<{ errorCode?: string }> };
199
+ };
200
+ const err = parsed.error;
201
+ if (!err) return null;
202
+ const detailCode = err.details?.find((d) => typeof d.errorCode === 'string')?.errorCode;
203
+ return detailCode ?? err.status ?? null;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+
209
+ /** A secret-free one-line error summary (status + error code, never the token). */
210
+ function errorSummary(status: number, body: string): string {
211
+ const code = fcmErrorCode(body);
212
+ return code ? `fcm ${status} ${code}` : `fcm ${status}`;
213
+ }
214
+
215
+ async function safeText(res: FcmResponseLike): Promise<string> {
216
+ try {
217
+ return await res.text();
218
+ } catch {
219
+ return '';
220
+ }
221
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * push-notifier-shared.ts — internal helpers shared by the FCM and APNs
3
+ * push-notifier implementations. Server-only (used only by modules that already
4
+ * reach for `node:crypto` / `node:http2`); never re-exported from the package
5
+ * entry. Centralized so the secret-redaction and payload-bounding rules have a
6
+ * single, hardenable source rather than drifting between the two transports.
7
+ */
8
+
9
+ /** Defensive cap on the free-form `reason` carried in a strand-wake payload. */
10
+ export const MAX_REASON_LEN = 256;
11
+
12
+ /** Base64url-encode the JSON form of an object (JWT header/claims segments). */
13
+ export function b64urlJson(obj: unknown): string {
14
+ return Buffer.from(JSON.stringify(obj)).toString('base64url');
15
+ }
16
+
17
+ /** A short, secret-free string for an unknown thrown value. */
18
+ export function errText(err: unknown): string {
19
+ return err instanceof Error ? err.message : String(err);
20
+ }
21
+
22
+ /**
23
+ * Redact a device token to a short, non-reversible prefix for debug lines — the
24
+ * full FCM/APNs token is a secret and must never reach a log.
25
+ */
26
+ export function redact(token: string): string {
27
+ return token.length <= 8 ? '…' : `${token.slice(0, 6)}…`;
28
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * push-notifier.ts — the platform-push **delivery** seam for strand-wake.
3
+ *
4
+ * Given a resolved mobile peer token, send one `strand-wake` data message over
5
+ * the right platform channel (FCM for Android, APNs for iOS). This module owns no
6
+ * policy — *who* to wake and *when* is the fan-out (`push-fanout.ts`). It is the
7
+ * reusable, credential-injected, transport-injected unit the fan-out constructs
8
+ * inside a participating `CadreNode` when push credentials are configured.
9
+ *
10
+ * `createPushNotifier` returns a router that dispatches by `msg.platform` to an
11
+ * `FcmPushNotifier` and/or `ApnsPushNotifier`, constructing only the
12
+ * implementations whose credentials are present. Failures are values, never
13
+ * thrown — mirroring `ServiceWakeResult` / `resolveDeviceToken`'s no-throw
14
+ * conventions so a best-effort fan-out can branch on the outcome.
15
+ *
16
+ * Server-only by construction: the FCM/APNs implementations reach for
17
+ * `node:crypto` / `node:http2`. They are never pulled into the RN/browser bundle
18
+ * because the cross-platform `index.ts` re-exports only the *types* here (a
19
+ * type-only re-export is erased at emit), and the only runtime constructor of a
20
+ * notifier is the in-package fan-out that runs inside a Node `CadreNode`. A
21
+ * cross-platform consumer imports the payload contract + types, never this value.
22
+ */
23
+
24
+ import type { PushPlatform, PushCredentials } from './types.js';
25
+ import type { StrandWakePayload } from './strand-wake-payload.js';
26
+ import { createFcmPushNotifier, type FcmPushDeps } from './push-notifier-fcm.js';
27
+ import { createApnsPushNotifier, type ApnsPushDeps } from './push-notifier-apns.js';
28
+
29
+ /** One strand-wake data message addressed to one device. */
30
+ export interface PushMessage {
31
+ /** The resolved `DeviceToken.token` for the target peer. */
32
+ token: string;
33
+ /** Which channel — selects FCM vs APNs. */
34
+ platform: PushPlatform;
35
+ /** The strand-wake payload `{ type:'strand-wake', strandId, reason }`. */
36
+ payload: StrandWakePayload;
37
+ }
38
+
39
+ /**
40
+ * Outcome of a single {@link PushNotifier.send}. A delivery failure is a value,
41
+ * never a thrown error. `unregistered: true` means the platform reported the
42
+ * token is permanently invalid (FCM 404 `UNREGISTERED` / 400 naming the token;
43
+ * APNs 410 `Unregistered` / 400 `BadDeviceToken`) — the caller should expire the
44
+ * stale `DeviceToken`. Any other failure is `unregistered: false` and is treated
45
+ * as best-effort/transient (no retry storm).
46
+ */
47
+ export type PushSendResult =
48
+ | { ok: true }
49
+ | { ok: false; unregistered: boolean; error: string };
50
+
51
+ export interface PushNotifier {
52
+ /** Send one strand-wake data message to one device. Never throws. */
53
+ send(msg: PushMessage): Promise<PushSendResult>;
54
+ /** Release transport resources (e.g. the APNs HTTP/2 session). */
55
+ close(): Promise<void>;
56
+ }
57
+
58
+ /**
59
+ * Per-platform transport/clock/log seams, injected by tests. Defaults are the
60
+ * real implementations (global `fetch` for FCM, a `node:http2` session for APNs).
61
+ */
62
+ export interface PushNotifierDeps {
63
+ fcm?: FcmPushDeps;
64
+ apns?: ApnsPushDeps;
65
+ }
66
+
67
+ /**
68
+ * Build a {@link PushNotifier} router over the configured credentials. Only the
69
+ * platforms whose credentials are present get a backing implementation; a `send`
70
+ * for an unconfigured platform returns a best-effort `no <platform> credentials`
71
+ * failure rather than throwing.
72
+ */
73
+ export function createPushNotifier(creds: PushCredentials, deps: PushNotifierDeps = {}): PushNotifier {
74
+ const fcm = creds.fcm ? createFcmPushNotifier(creds.fcm, deps.fcm) : undefined;
75
+ const apns = creds.apns ? createApnsPushNotifier(creds.apns, deps.apns) : undefined;
76
+
77
+ async function send(msg: PushMessage): Promise<PushSendResult> {
78
+ if (msg.platform === 'fcm') return fcm ? fcm.send(msg) : noCreds('fcm');
79
+ if (msg.platform === 'apns') return apns ? apns.send(msg) : noCreds('apns');
80
+ return { ok: false, unregistered: false, error: `unknown platform ${String(msg.platform)}` };
81
+ }
82
+
83
+ async function close(): Promise<void> {
84
+ await Promise.all([fcm?.close(), apns?.close()]);
85
+ }
86
+
87
+ return { send, close };
88
+ }
89
+
90
+ /** Best-effort no-op result for a platform with no configured credentials. */
91
+ function noCreds(platform: PushPlatform): PushSendResult {
92
+ return { ok: false, unregistered: false, error: `no ${platform} credentials` };
93
+ }
@@ -24,7 +24,7 @@ export class SchemaVerificationError extends Error {
24
24
  */
25
25
  function schemaDigest(schema: string, version: string): string {
26
26
  const payload = JSON.stringify({ schema, version });
27
- return digest(payload, 'sha256', 'utf8', 'base64url') as string;
27
+ return digest([payload], 'sha256', 'base64url') as string;
28
28
  }
29
29
 
30
30
  /**
@@ -64,14 +64,28 @@ export function verifySchema(schema: string, version: string, signature: string,
64
64
  * Assert that an SAppConfig has a valid schema signature.
65
65
  * Throws SchemaVerificationError on failure.
66
66
  *
67
+ * Fail-closed by default: when `options.requireSignature` is not explicitly
68
+ * `false`, an absent signature is rejected with reason `'missing signature'`,
69
+ * distinct from the `'invalid signature'` (tampered/wrong-key) case. The
70
+ * relaxation (`requireSignature: false`) only excuses *absence* of a signature;
71
+ * a present-but-bad signature still throws.
72
+ *
67
73
  * @param sAppConfig - The sApp configuration to verify
68
- * @throws SchemaVerificationError if the signature is invalid
74
+ * @param options - Verification policy; `requireSignature` defaults to `true`
75
+ * @throws SchemaVerificationError if the signature is missing (when required) or invalid
69
76
  */
70
- export function assertSchemaSignature(sAppConfig: SAppConfig): void {
77
+ export function assertSchemaSignature(
78
+ sAppConfig: SAppConfig,
79
+ options?: { requireSignature?: boolean }
80
+ ): void {
71
81
  const { id, version, schema, signature } = sAppConfig;
82
+ const requireSignature = options?.requireSignature ?? true;
72
83
 
73
84
  if (!signature) {
74
- log('No signature provided for %s v%s — skipping verification', id, version);
85
+ if (requireSignature) {
86
+ throw new SchemaVerificationError(id ?? '', version, 'missing signature');
87
+ }
88
+ log('No signature provided for %s v%s — skipping verification (policy relaxed)', id, version);
75
89
  return;
76
90
  }
77
91