agl 43.6.0 → 43.8.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 (166) hide show
  1. package/changelog.md +27 -0
  2. package/dist_serve/bundle.js +1801 -1783
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/interfaces.d.ts +35 -0
  6. package/dist_ts/aglapi/interfaces.js +9 -1
  7. package/dist_ts/classes.accountsactions.d.ts +3 -1
  8. package/dist_ts/classes.accountsactions.js +17 -1
  9. package/dist_ts/classes.apnsclient.d.ts +97 -0
  10. package/dist_ts/classes.apnsclient.js +363 -0
  11. package/dist_ts/classes.authmodels.js +19 -6
  12. package/dist_ts/classes.authstore.js +15 -2
  13. package/dist_ts/classes.cli.js +8 -1
  14. package/dist_ts/classes.controller.d.ts +33 -6
  15. package/dist_ts/classes.controller.js +254 -12
  16. package/dist_ts/classes.controllerdevices.d.ts +35 -7
  17. package/dist_ts/classes.controllerdevices.js +86 -13
  18. package/dist_ts/classes.controllerpush.d.ts +111 -0
  19. package/dist_ts/classes.controllerpush.js +299 -0
  20. package/dist_ts/classes.fcmclient.d.ts +78 -0
  21. package/dist_ts/classes.fcmclient.js +278 -0
  22. package/dist_ts/classes.inbox.d.ts +10 -2
  23. package/dist_ts/classes.inbox.js +9 -2
  24. package/dist_ts/classes.inferencerouter.d.ts +21 -3
  25. package/dist_ts/classes.inferencerouter.js +40 -17
  26. package/dist_ts/classes.inferenceservice.js +2 -2
  27. package/dist_ts/classes.mcpclient.d.ts +5 -0
  28. package/dist_ts/classes.mcpclient.js +18 -6
  29. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
  30. package/dist_ts/classes.mcpcontrollerhost.js +19 -1
  31. package/dist_ts/classes.mcpvalidation.js +4 -1
  32. package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
  33. package/dist_ts/classes.mcpworkercaller.js +26 -4
  34. package/dist_ts/classes.pushdelivery.d.ts +115 -0
  35. package/dist_ts/classes.pushdelivery.js +311 -0
  36. package/dist_ts/classes.pushhandover.d.ts +46 -0
  37. package/dist_ts/classes.pushhandover.js +131 -0
  38. package/dist_ts/classes.pushregistrations.d.ts +96 -0
  39. package/dist_ts/classes.pushregistrations.js +263 -0
  40. package/dist_ts/classes.pushsettings.d.ts +125 -0
  41. package/dist_ts/classes.pushsettings.js +377 -0
  42. package/dist_ts/classes.workercallers.d.ts +73 -2
  43. package/dist_ts/classes.workercallers.js +354 -43
  44. package/dist_ts/driver/classes.directreports.d.ts +5 -0
  45. package/dist_ts/driver/classes.directreports.js +3 -2
  46. package/dist_ts/fleet/classes.workerlaunches.d.ts +6 -4
  47. package/dist_ts/fleet/classes.workerlaunches.js +10 -9
  48. package/dist_ts/fleet/classes.workers.d.ts +12 -2
  49. package/dist_ts/fleet/classes.workers.js +82 -2
  50. package/dist_ts/functions.deviceapi.d.ts +23 -3
  51. package/dist_ts/functions.deviceapi.js +41 -3
  52. package/dist_ts/functions.inferencecli.js +2 -1
  53. package/dist_ts/functions.pushcli.d.ts +43 -0
  54. package/dist_ts/functions.pushcli.js +201 -0
  55. package/dist_ts/functions.pushcredentials.d.ts +53 -0
  56. package/dist_ts/functions.pushcredentials.js +111 -0
  57. package/dist_ts/functions.pushwire.d.ts +8 -0
  58. package/dist_ts/functions.pushwire.js +83 -0
  59. package/dist_ts/functions.remotecli.d.ts +2 -2
  60. package/dist_ts/functions.remotecli.js +4 -4
  61. package/dist_ts/functions.workercallervalidation.js +3 -2
  62. package/dist_ts/functions.workerprocessproof.d.ts +12 -0
  63. package/dist_ts/functions.workerprocessproof.js +32 -1
  64. package/dist_ts/interfaces.auth.d.ts +27 -3
  65. package/dist_ts/interfaces.auth.js +10 -1
  66. package/dist_ts/interfaces.lifecycle.d.ts +7 -1
  67. package/dist_ts/interfaces.push.d.ts +69 -0
  68. package/dist_ts/interfaces.push.js +25 -0
  69. package/dist_ts/plugins.d.ts +5 -2
  70. package/dist_ts/plugins.js +7 -3
  71. package/dist_ts_authswitch/authority-contract.d.ts +26 -0
  72. package/dist_ts_authswitch/authority-contract.js +1 -1
  73. package/dist_ts_authswitch/authority-overview.d.ts +8 -0
  74. package/dist_ts_authswitch/authority-overview.js +10 -4
  75. package/dist_ts_authswitch/authority-placement.d.ts +16 -9
  76. package/dist_ts_authswitch/authority-placement.js +10 -7
  77. package/dist_ts_authswitch/authority-priority.d.ts +20 -0
  78. package/dist_ts_authswitch/authority-priority.js +21 -0
  79. package/dist_ts_authswitch/classes.authoritybroker.d.ts +7 -0
  80. package/dist_ts_authswitch/classes.authoritybroker.js +26 -2
  81. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  82. package/dist_ts_authswitch/classes.authoritycli.js +43 -3
  83. package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
  84. package/dist_ts_authswitch/classes.authorityclient.js +12 -4
  85. package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
  86. package/dist_ts_authswitch/classes.authoritydatabase.d.ts +6 -0
  87. package/dist_ts_authswitch/classes.authoritydatabase.js +13 -2
  88. package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
  89. package/dist_ts_authswitch/classes.authoritymodels.js +17 -8
  90. package/dist_ts_interfaces/devices.d.ts +178 -2
  91. package/dist_ts_interfaces/devices.js +24 -2
  92. package/dist_ts_interfaces/index.d.ts +1 -0
  93. package/dist_ts_interfaces/index.js +2 -1
  94. package/dist_ts_interfaces/mcprequests.d.ts +3 -2
  95. package/dist_ts_interfaces/mcprequests.js +3 -1
  96. package/dist_ts_interfaces/push.d.ts +166 -0
  97. package/dist_ts_interfaces/push.js +24 -0
  98. package/dist_ts_interfaces/requests.accounts.d.ts +19 -0
  99. package/dist_ts_interfaces/requests.accounts.js +1 -1
  100. package/dist_ts_interfaces/requests.d.ts +2 -2
  101. package/dist_ts_interfaces/requests.js +1 -1
  102. package/dist_ts_interfaces/workercallers.d.ts +43 -3
  103. package/docs/authswitch.md +25 -0
  104. package/package.json +1 -1
  105. package/readme.md +93 -16
  106. package/ts/00_commitinfo_data.ts +1 -1
  107. package/ts/aglapi/interfaces.ts +8 -0
  108. package/ts/classes.accountsactions.ts +25 -0
  109. package/ts/classes.apnsclient.ts +389 -0
  110. package/ts/classes.authmodels.ts +21 -5
  111. package/ts/classes.authstore.ts +14 -1
  112. package/ts/classes.cli.ts +7 -0
  113. package/ts/classes.controller.ts +277 -10
  114. package/ts/classes.controllerdevices.ts +94 -12
  115. package/ts/classes.controllerpush.ts +351 -0
  116. package/ts/classes.fcmclient.ts +292 -0
  117. package/ts/classes.inbox.ts +13 -2
  118. package/ts/classes.inferencerouter.ts +61 -16
  119. package/ts/classes.inferenceservice.ts +1 -1
  120. package/ts/classes.mcpclient.ts +20 -5
  121. package/ts/classes.mcpcontrollerhost.ts +20 -0
  122. package/ts/classes.mcpvalidation.ts +2 -0
  123. package/ts/classes.mcpworkercaller.ts +24 -2
  124. package/ts/classes.pushdelivery.ts +378 -0
  125. package/ts/classes.pushhandover.ts +98 -0
  126. package/ts/classes.pushregistrations.ts +244 -0
  127. package/ts/classes.pushsettings.ts +428 -0
  128. package/ts/classes.workercallers.ts +329 -37
  129. package/ts/driver/classes.directreports.ts +7 -1
  130. package/ts/fleet/classes.workerlaunches.ts +9 -7
  131. package/ts/fleet/classes.workers.ts +65 -2
  132. package/ts/functions.deviceapi.ts +52 -2
  133. package/ts/functions.inferencecli.ts +1 -0
  134. package/ts/functions.pushcli.ts +212 -0
  135. package/ts/functions.pushcredentials.ts +129 -0
  136. package/ts/functions.pushwire.ts +106 -0
  137. package/ts/functions.remotecli.ts +3 -2
  138. package/ts/functions.workercallervalidation.ts +2 -1
  139. package/ts/functions.workerprocessproof.ts +34 -0
  140. package/ts/interfaces.auth.ts +27 -3
  141. package/ts/interfaces.lifecycle.ts +7 -1
  142. package/ts/interfaces.push.ts +78 -0
  143. package/ts/plugins.ts +6 -1
  144. package/ts_authswitch/authority-contract.ts +21 -0
  145. package/ts_authswitch/authority-overview.ts +19 -5
  146. package/ts_authswitch/authority-placement.ts +18 -10
  147. package/ts_authswitch/authority-priority.ts +25 -0
  148. package/ts_authswitch/classes.authoritybroker.ts +26 -1
  149. package/ts_authswitch/classes.authoritycli.ts +48 -2
  150. package/ts_authswitch/classes.authorityclient.ts +14 -4
  151. package/ts_authswitch/classes.authoritydaemon.ts +8 -1
  152. package/ts_authswitch/classes.authoritydatabase.ts +11 -1
  153. package/ts_authswitch/classes.authoritymodels.ts +17 -6
  154. package/ts_authswitch/readme.md +1 -1
  155. package/ts_interfaces/devices.schema.json +327 -0
  156. package/ts_interfaces/devices.ts +206 -1
  157. package/ts_interfaces/index.ts +1 -0
  158. package/ts_interfaces/mcprequests.ts +3 -0
  159. package/ts_interfaces/push.ts +162 -0
  160. package/ts_interfaces/requests.accounts.ts +17 -0
  161. package/ts_interfaces/requests.ts +2 -0
  162. package/ts_interfaces/workercallers.ts +34 -2
  163. package/ts_web/00_commitinfo_data.ts +1 -1
  164. package/ts_web/accounts.plugins.ts +4 -2
  165. package/ts_web/classes.accountsreadmodel.ts +36 -2
  166. package/ts_web/elements.accounts.ts +48 -0
@@ -0,0 +1,351 @@
1
+ import {
2
+ devicePushReportSentence,
3
+ devicePushSentences,
4
+ devicePushSummarySentence,
5
+ type IDevicePushInboxData,
6
+ type IDevicePushReportData,
7
+ type TDevicePushData,
8
+ type TDevicePushPlatform,
9
+ } from '../ts_interfaces/devices.js';
10
+ import type { IDirectReport } from '../ts_interfaces/directreports.js';
11
+ import {
12
+ controllerInboxLimits,
13
+ type IControllerInboxSnapshot,
14
+ type TControllerInboxDelta,
15
+ type TControllerInboxItem,
16
+ type TControllerInboxWhere,
17
+ } from '../ts_interfaces/index.js';
18
+ import { apnsRequest } from './classes.apnsclient.js';
19
+ import { fcmMessage } from './classes.fcmclient.js';
20
+ import { inboxTitle } from './classes.inbox.js';
21
+ import type { IPushDeliveryTarget } from './classes.pushdelivery.js';
22
+ import { pushKeySubjects, pushNotificationKey, type IControllerPushTarget } from './classes.pushregistrations.js';
23
+
24
+ /**
25
+ * The Inbox's push trigger (AGL-1639): it turns the deltas the Inbox publishes, and the direct reports' new results,
26
+ * into notifications for the registrations of this controller's paired devices, and hands them to the delivery, which
27
+ * returns at once. It never reads the Inbox's sources: an item that came is one the Inbox published, by id, and an item
28
+ * that left is one it removed. What it knows of the Inbox is the ids it saw in this process; only a clean stop hands
29
+ * over what it announced, and what the handover it started from named that it has not met yet
30
+ * (`IControllerPushHandover`): the next start does not announce again an item that still waits with the same id and
31
+ * `since`. Every other item that waits after a start goes out once more under its key, replacing what a device shows:
32
+ * after a kill, a failed handover, or an item stamped anew.
33
+ */
34
+
35
+ /** More new items than this in one pass are announced by one summary instead of one notification each. */
36
+ export const pushSummaryThreshold = 4;
37
+
38
+ /**
39
+ * A `clear`'s keys, space-separated, stay within this many bytes, so the payload stays under Apple's 4096 bytes and
40
+ * FCM's 4096 bytes of data (about 80 keys of 43 characters).
41
+ */
42
+ export const pushClearKeysMaximumBytes = 3584;
43
+
44
+ /**
45
+ * Where a clean stop leaves what the trigger hands over, item id to `since`, for the next start (`takePushHandover` and
46
+ * `keepPushHandover` in `ts/classes.pushhandover.ts`). `take` answers what the last clean stop left and removes it, none
47
+ * when no clean stop left any; `keep` replaces it.
48
+ */
49
+ export interface IControllerPushHandover {
50
+ take(): Promise<ReadonlyMap<string, number> | undefined>;
51
+ keep(announcedArg: ReadonlyMap<string, number>): Promise<void>;
52
+ }
53
+
54
+ /** What the trigger asks of the delivery (`ControllerPushDelivery`). */
55
+ export interface IControllerPushDelivery {
56
+ available(platformArg: TDevicePushPlatform): boolean;
57
+ send(targetArg: IPushDeliveryTarget, payloadArg: TDevicePushData): void;
58
+ withdraw(deviceIdArg: string, keysArg: readonly string[]): void;
59
+ }
60
+
61
+ export interface IControllerPushOptions {
62
+ /** The registrations of this controller's paired devices, never another controller's (`ControllerDevices.pushTargets`). */
63
+ targets(): Promise<readonly IControllerPushTarget[]>;
64
+ delivery: IControllerPushDelivery;
65
+ /** Whether notifications carry previews (`ControllerPushSettings.previews`). */
66
+ previews(): boolean;
67
+ /** Read once as the trigger starts, before any change is sent, and written once by `stop`. */
68
+ handover: IControllerPushHandover;
69
+ /** A failure no caller sees: a registration read that failed, a handover that was not there or not kept, a fault of the trigger. */
70
+ fault(errorArg: unknown): void;
71
+ }
72
+
73
+ /** What one Inbox pass changed, as the trigger sends it. */
74
+ interface IInboxChange {
75
+ added: TControllerInboxItem[];
76
+ removed: string[];
77
+ /** The Inbox's count after the pass: the badge. */
78
+ total: number;
79
+ previews: boolean;
80
+ }
81
+
82
+ /** Where an item lives, as a previewed notification's title: the session, the driver or the ticket. */
83
+ const pushPlace = (whereArg: TControllerInboxWhere): string => {
84
+ switch (whereArg.kind) {
85
+ case 'conversation':
86
+ case 'native':
87
+ return whereArg.name;
88
+ case 'child':
89
+ return `${whereArg.childName} in ${whereArg.name}`;
90
+ case 'driver':
91
+ return 'Driver';
92
+ case 'ticket':
93
+ return `${whereArg.ticketKey} · ${whereArg.ticketTitle}`;
94
+ }
95
+ };
96
+
97
+ /** Whether a payload fits both push services' limits, as their senders build the request. */
98
+ const pushPayloadFits = (payloadArg: TDevicePushData): boolean => (
99
+ apnsRequest('com.modelprofile.harness', payloadArg, 0) !== undefined && fcmMessage('token', payloadArg, 0, 0) !== undefined
100
+ );
101
+
102
+ /** At most `charactersArg` characters of one line, its end marked when it was cut. */
103
+ const cut = (textArg: string, charactersArg: number): string => {
104
+ const characters = [...textArg];
105
+ return characters.length <= charactersArg ? textArg : `${characters.slice(0, Math.max(0, charactersArg - 1)).join('').trimEnd()}…`;
106
+ };
107
+
108
+ /**
109
+ * A previewed notification within the push services' limits: its title and body cut shorter until it fits (Apple
110
+ * repeats both in `aps`), or, for an item whose id alone leaves no room, `plainArg`.
111
+ */
112
+ const fitted = <TPayload extends IDevicePushInboxData | IDevicePushReportData>(
113
+ plainArg: TPayload,
114
+ previewArg: (charactersArg: number) => TPayload,
115
+ ): TPayload => {
116
+ for (let characters: number = controllerInboxLimits.titleChars; characters > 0; characters = Math.floor(characters / 2)) {
117
+ const payload = previewArg(characters);
118
+ if (pushPayloadFits(payload)) return payload;
119
+ }
120
+ return plainArg;
121
+ };
122
+
123
+ /** The device a registration names, as the delivery sends to it: its token never leaves the host but to its push service. */
124
+ const deliveryTarget = (targetArg: IControllerPushTarget): IPushDeliveryTarget => ({
125
+ deviceId: targetArg.deviceId,
126
+ platform: targetArg.platform,
127
+ ...(targetArg.environment === undefined ? {} : { environment: targetArg.environment }),
128
+ token: targetArg.token,
129
+ });
130
+
131
+ const messageOf = (errorArg: unknown): string => (errorArg instanceof Error ? errorArg.message : String(errorArg));
132
+
133
+ /** Space-separated keys in groups of at most `pushClearKeysMaximumBytes`. */
134
+ export const pushClearChunks = (keysArg: readonly string[]): string[] => {
135
+ const chunks: string[] = [];
136
+ let current = '';
137
+ for (const key of keysArg) {
138
+ const next = current === '' ? key : `${current} ${key}`;
139
+ if (current !== '' && Buffer.byteLength(next, 'utf8') > pushClearKeysMaximumBytes) {
140
+ chunks.push(current);
141
+ current = key;
142
+ } else {
143
+ current = next;
144
+ }
145
+ }
146
+ if (current !== '') chunks.push(current);
147
+ return chunks;
148
+ };
149
+
150
+ export class ControllerPush {
151
+ /** The ids of the items the Inbox published last, as this trigger saw them. */
152
+ private known = new Set<string>();
153
+ private epoch?: string;
154
+ /**
155
+ * The items handed to the delivery for at least one registration, alone or under a summary, that still wait: id to the
156
+ * `since` they were announced with. What `stop` hands over.
157
+ */
158
+ private readonly announced = new Map<string, number>();
159
+ /**
160
+ * What the handover this process started from named that it has not met yet: handed over again by `stop`, so a
161
+ * clean stop before every item came back loses none. A pair goes once its id comes, with the same `since` or not.
162
+ */
163
+ private handedOver = new Map<string, number>();
164
+ /** Changes are sent one after the other, in the order the Inbox published them, after the handover was read. */
165
+ private tail: Promise<void>;
166
+ private stopped = false;
167
+ private stopping?: Promise<void>;
168
+
169
+ constructor(private readonly options: IControllerPushOptions) {
170
+ this.tail = this.receiveHandover();
171
+ }
172
+
173
+ /**
174
+ * Whether a notification could go out now: a registration of this controller's devices on a platform the host holds
175
+ * a usable credential for. While none could, the Inbox runs as it runs without push: it passes only for a connected
176
+ * browser or device.
177
+ */
178
+ public async receives(): Promise<boolean> {
179
+ if (this.stopped) return false;
180
+ const { delivery } = this.options;
181
+ if (!delivery.available('apns') && !delivery.available('fcm')) return false;
182
+ try {
183
+ return (await this.options.targets()).some((targetArg) => delivery.available(targetArg.platform));
184
+ } catch (errorArg) {
185
+ this.options.fault(errorArg);
186
+ return false;
187
+ }
188
+ }
189
+
190
+ /**
191
+ * One delta as the Inbox published it, while the Inbox publishes it: an item that came is a notification (more than
192
+ * `pushSummaryThreshold` in one pass, one summary), an item that left a `clear` and the withdrawal of its notification
193
+ * still queued, a changed item nothing. `currentArg` answers what the Inbox published, read only for a `reset` or
194
+ * another epoch. Returns at once; it never throws into the Inbox's pass.
195
+ */
196
+ public inboxChanged(deltaArg: TControllerInboxDelta, currentArg: () => IControllerInboxSnapshot | undefined): void {
197
+ if (this.stopped) return;
198
+ try {
199
+ const change = this.change(deltaArg, currentArg);
200
+ if (!change || (change.added.length === 0 && change.removed.length === 0)) return;
201
+ this.tail = this.tail.then(async () => {
202
+ // In the order the Inbox published: an item that left is no longer announced, and one the last clean stop had
203
+ // announced that waits as it did then is not announced again.
204
+ for (const id of change.removed) this.announced.delete(id);
205
+ const added = change.added.filter((itemArg) => !this.metAgain(itemArg));
206
+ if (this.stopped || (added.length === 0 && change.removed.length === 0)) return;
207
+ const targets = await this.availableTargets();
208
+ if (this.stopped || targets.length === 0) return;
209
+ this.sendInboxChange({ ...change, added }, targets);
210
+ for (const item of added) this.announced.set(item.id, item.since);
211
+ }).catch((errorArg: unknown) => { this.options.fault(errorArg); });
212
+ } catch (errorArg) {
213
+ this.options.fault(errorArg);
214
+ }
215
+ }
216
+
217
+ /** A direct report's new `result:` line: a notification for the devices that asked for results, with no badge. */
218
+ public reportResult(reportArg: IDirectReport): void {
219
+ if (this.stopped || reportArg.latestResult === undefined) return;
220
+ const { name } = reportArg;
221
+ const text = reportArg.latestResult.text;
222
+ const previews = this.options.previews();
223
+ this.enqueue(async (targetsArg) => {
224
+ for (const target of targetsArg) {
225
+ if (!target.reports) continue;
226
+ const key = pushNotificationKey(target.salt, pushKeySubjects.report(name));
227
+ const plain: IDevicePushReportData = { type: 'report', key, body: devicePushReportSentence };
228
+ this.options.delivery.send(deliveryTarget(target), previews
229
+ ? fitted(plain, (charactersArg) => ({ ...plain, title: cut(inboxTitle(name), charactersArg), body: cut(inboxTitle(text), charactersArg) }))
230
+ : plain);
231
+ }
232
+ });
233
+ }
234
+
235
+ /**
236
+ * Sends nothing more, waits for the change being sent, and hands over, once, what was announced and still waits and
237
+ * what the handover this process started from named that it has not met yet (an announced pair wins). Never rejects: a
238
+ * handover that was not kept is a fault, and the next start announces what waits once more.
239
+ */
240
+ public stop(): Promise<void> {
241
+ this.stopped = true;
242
+ this.stopping ??= (async () => {
243
+ await this.tail;
244
+ try {
245
+ await this.options.handover.keep(new Map([...this.handedOver, ...this.announced]));
246
+ } catch (errorArg) {
247
+ this.options.fault(new Error(`The push handover was not kept, so the next start announces what still waits once more: ${messageOf(errorArg)}`));
248
+ }
249
+ })();
250
+ return this.stopping;
251
+ }
252
+
253
+ /**
254
+ * Reads what the last clean stop handed over; without it every item that waits is announced, as after a kill. A missing
255
+ * handover is recorded only while a notification could go out (`receives`): on a host that cannot send it changes
256
+ * nothing. One that does not read is always recorded.
257
+ */
258
+ private async receiveHandover(): Promise<void> {
259
+ try {
260
+ const handover = await this.options.handover.take();
261
+ if (handover === undefined) {
262
+ if (await this.receives()) {
263
+ this.options.fault(new Error('No push handover from a clean stop: the items that still wait are announced once more.'));
264
+ }
265
+ return;
266
+ }
267
+ this.handedOver = new Map(handover);
268
+ } catch (errorArg) {
269
+ this.options.fault(new Error(`The push handover could not be read, so the items that still wait are announced once more: ${messageOf(errorArg)}`));
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Whether the handover named the item with the same id and `since`: it is then not announced again, and is announced
275
+ * in this process. An item stamped anew (another `since`) is announced as a new one; either way the pair has been met
276
+ * and is no longer handed over.
277
+ */
278
+ private metAgain(itemArg: TControllerInboxItem): boolean {
279
+ const since = this.handedOver.get(itemArg.id);
280
+ if (since === undefined) return false;
281
+ this.handedOver.delete(itemArg.id);
282
+ if (since !== itemArg.since) return false;
283
+ this.announced.set(itemArg.id, itemArg.since);
284
+ return true;
285
+ }
286
+
287
+ /** The registrations of this controller's devices on a platform the host can send on now. */
288
+ private async availableTargets(): Promise<readonly IControllerPushTarget[]> {
289
+ return (await this.options.targets()).filter((targetArg) => this.options.delivery.available(targetArg.platform));
290
+ }
291
+
292
+ /** The items that came and left with the delta, against the ids this trigger saw last. */
293
+ private change(deltaArg: TControllerInboxDelta, currentArg: () => IControllerInboxSnapshot | undefined): IInboxChange | undefined {
294
+ const previews = this.options.previews();
295
+ if ('reset' in deltaArg || deltaArg.epoch !== this.epoch) {
296
+ const snapshot = currentArg();
297
+ if (!snapshot) return undefined;
298
+ const ids = new Set(snapshot.items.map((itemArg) => itemArg.id));
299
+ const added = snapshot.items.filter((itemArg) => !this.known.has(itemArg.id));
300
+ const removed = [...this.known].filter((idArg) => !ids.has(idArg));
301
+ this.known = ids;
302
+ this.epoch = snapshot.epoch;
303
+ return { added, removed, total: snapshot.total, previews };
304
+ }
305
+ const added = deltaArg.upserts.filter((itemArg) => !this.known.has(itemArg.id));
306
+ const removed = deltaArg.removed.filter((idArg) => this.known.has(idArg));
307
+ for (const item of added) this.known.add(item.id);
308
+ for (const id of removed) this.known.delete(id);
309
+ return { added, removed, total: deltaArg.total, previews };
310
+ }
311
+
312
+ /** Reads the registrations once for the work, after the work queued before it; a failure is reported, never thrown. */
313
+ private enqueue(workArg: (targetsArg: readonly IControllerPushTarget[]) => Promise<void>): void {
314
+ this.tail = this.tail.then(async () => {
315
+ if (this.stopped) return;
316
+ const targets = await this.availableTargets();
317
+ if (this.stopped || targets.length === 0) return;
318
+ await workArg(targets);
319
+ }).catch((errorArg: unknown) => { this.options.fault(errorArg); });
320
+ }
321
+
322
+ private sendInboxChange(changeArg: IInboxChange, targetsArg: readonly IControllerPushTarget[]): void {
323
+ const { delivery } = this.options;
324
+ const badge = String(changeArg.total);
325
+ for (const registration of targetsArg) {
326
+ const target = deliveryTarget(registration);
327
+ const summaryKey = pushNotificationKey(registration.salt, pushKeySubjects.summary);
328
+ if (changeArg.removed.length > 0) {
329
+ const keys = changeArg.removed.map((idArg) => pushNotificationKey(registration.salt, idArg));
330
+ // Nothing waits any more: the summary, which says new items wait, goes too.
331
+ if (changeArg.total === 0) keys.push(summaryKey);
332
+ delivery.withdraw(target.deviceId, keys);
333
+ for (const chunk of pushClearChunks(keys)) delivery.send(target, { type: 'clear', keys: chunk, badge });
334
+ }
335
+ if (changeArg.added.length > pushSummaryThreshold) {
336
+ delivery.send(target, { type: 'summary', key: summaryKey, count: String(changeArg.added.length), badge, body: devicePushSummarySentence });
337
+ continue;
338
+ }
339
+ for (const item of changeArg.added) {
340
+ const plain: IDevicePushInboxData = {
341
+ type: 'inbox', key: pushNotificationKey(registration.salt, item.id), kind: item.kind, badge, body: devicePushSentences[item.kind],
342
+ };
343
+ delivery.send(target, changeArg.previews
344
+ ? fitted(plain, (charactersArg) => ({
345
+ ...plain, title: cut(inboxTitle(pushPlace(item.where)), charactersArg), body: cut(item.title, charactersArg), itemId: item.id,
346
+ }))
347
+ : plain);
348
+ }
349
+ }
350
+ }
351
+ }
@@ -0,0 +1,292 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { TDevicePushData } from '../ts_interfaces/devices.js';
3
+ import type { IFcmCredential } from './classes.pushsettings.js';
4
+ import {
5
+ googleHosts,
6
+ isPushVendorReason,
7
+ pushRequestTimeoutMs,
8
+ pushServiceEndpoints,
9
+ retryAfterMs,
10
+ type IPushEndpoints,
11
+ type IPushSender,
12
+ type IPushSendTarget,
13
+ type TGoogleHost,
14
+ type TPushSendResult,
15
+ } from './interfaces.push.js';
16
+
17
+ /**
18
+ * Firebase Cloud Messaging, spoken directly (AGL-1639; Google's "Using OAuth 2.0 for Server to Server Applications" and
19
+ * the FCM HTTP v1 reference): the service account signs an RS256 JWT for the messaging scope, Google's token endpoint
20
+ * trades it for an access token (an hour), and `POST /v1/projects/<project>/messages:send` sends a data-only message,
21
+ * every value a string, which the Android app turns into its notification.
22
+ */
23
+
24
+ export const fcmScope = 'https://www.googleapis.com/auth/firebase.messaging';
25
+ /** The JWT's audience and the endpoint the assertion goes to, whatever the key file names. */
26
+ export const googleTokenAudience = `https://${googleHosts.token}/token`;
27
+ /** Google: a data payload, keys and values counted, is at most 4096 bytes. */
28
+ export const fcmDataMaximumBytes = 4096;
29
+ /** An access token is used until five minutes before Google said it expires. */
30
+ const accessTokenMarginMs = 5 * 60_000;
31
+ /** Google's answers are small JSON objects; anything past this is not read. */
32
+ const maximumAnswerBytes = 64 * 1024;
33
+ /** Keys FCM reserves in a data payload. */
34
+ const reservedDataKey = (keyArg: string): boolean => keyArg === 'from' || keyArg === 'message_type' || keyArg.startsWith('google.')
35
+ || keyArg.startsWith('gcm.') || keyArg === 'collapse_key';
36
+
37
+ /**
38
+ * The FCM v1 request body for a notification: a data-only message to the registration token (the payload's values as
39
+ * they are, all strings), `android.priority` HIGH for what a person acts on (`inbox`, `summary`, `test`) and NORMAL for
40
+ * a report's result and a `clear`, and a `ttl` up to `expiresAtArg`. No collapse key: FCM keeps at most four of them per
41
+ * device, and the app replaces a notification by its tag (the payload's key) itself. None when the payload breaks FCM's
42
+ * limits.
43
+ */
44
+ export const fcmMessage = (tokenArg: string, payloadArg: TDevicePushData, expiresAtArg: number, nowArg: number): Record<string, unknown> | undefined => {
45
+ const entries = Object.entries(payloadArg);
46
+ if (entries.some(([keyArg, valueArg]) => typeof valueArg !== 'string' || reservedDataKey(keyArg))) return undefined;
47
+ const size = entries.reduce((totalArg, [keyArg, valueArg]) => totalArg + Buffer.byteLength(keyArg, 'utf8') + Buffer.byteLength(valueArg as string, 'utf8'), 0);
48
+ if (size > fcmDataMaximumBytes) return undefined;
49
+ const urgent = payloadArg.type === 'inbox' || payloadArg.type === 'summary' || payloadArg.type === 'test';
50
+ return {
51
+ message: {
52
+ token: tokenArg,
53
+ data: Object.fromEntries(entries),
54
+ android: {
55
+ priority: urgent ? 'HIGH' : 'NORMAL',
56
+ ttl: `${Math.max(0, Math.floor((expiresAtArg - nowArg) / 1000))}s`,
57
+ },
58
+ },
59
+ };
60
+ };
61
+
62
+ interface IGoogleError {
63
+ status?: string;
64
+ errorCode?: string;
65
+ }
66
+
67
+ /** An FCM or Google error answer's canonical status and FCM error code; nothing of its message. */
68
+ const readGoogleError = (bodyArg: Buffer): IGoogleError => {
69
+ try {
70
+ const answer = JSON.parse(bodyArg.toString('utf8')) as { error?: { status?: unknown; details?: unknown } };
71
+ const details = Array.isArray(answer?.error?.details) ? answer.error.details as Array<Record<string, unknown>> : [];
72
+ const fcmError = details.find((detailArg) => detailArg?.['@type'] === 'type.googleapis.com/google.firebase.fcm.v1.FcmError');
73
+ return {
74
+ ...(isPushVendorReason(answer?.error?.status) ? { status: answer.error.status } : {}),
75
+ ...(isPushVendorReason(fcmError?.errorCode) ? { errorCode: fcmError.errorCode } : {}),
76
+ };
77
+ } catch {
78
+ return {};
79
+ }
80
+ };
81
+
82
+ /** What an FCM send answer means for the send (Google's FCM error codes). A 401 that is not a third party's is the access token's. */
83
+ export const fcmResult = (statusArg: number, errorArg: IGoogleError, retryAfterArg?: number): TPushSendResult => {
84
+ const code = errorArg.errorCode ?? errorArg.status;
85
+ const vendorReason = code === undefined ? {} : { vendorReason: code };
86
+ const retry = retryAfterArg === undefined ? {} : { retryAfterMs: retryAfterArg };
87
+ if (statusArg >= 200 && statusArg < 300) return { outcome: 'delivered' };
88
+ if (errorArg.errorCode === 'UNREGISTERED') return { outcome: 'unregistered', vendorReason: 'UNREGISTERED' };
89
+ // The registration is another sender's, or a third party (APNs, web push) refused it: this notification only.
90
+ if (errorArg.errorCode === 'SENDER_ID_MISMATCH' || errorArg.errorCode === 'THIRD_PARTY_AUTH_ERROR'
91
+ || errorArg.errorCode === 'THIRD_PARTY_PERMISSION_DENIED') return { outcome: 'refused', ...vendorReason };
92
+ // The access token is refused after it was asked anew, or the service account may not send for the project: the credential.
93
+ if (statusArg === 401 || statusArg === 403) return { outcome: 'credential_refused', ...vendorReason };
94
+ if (statusArg === 429) return { outcome: 'rate_limited', ...vendorReason, ...retry };
95
+ // A NOT_FOUND without `UNREGISTERED` names neither the token nor the credential for certain: this notification only.
96
+ if (statusArg === 400 || statusArg === 404) return { outcome: 'refused', ...vendorReason };
97
+ return { outcome: 'service_failed', ...vendorReason, ...retry };
98
+ };
99
+
100
+ /**
101
+ * The token endpoint's errors that name the service account or its key (Google's "JWT error codes"): `invalid_grant`
102
+ * (the key is not the account's, or deleted, disabled or expired; the account or its email is unknown), `invalid_client`,
103
+ * `unauthorized_client`, `disabled_client` and `deleted_client`. Google gives `invalid_grant` for an assertion outside
104
+ * "a reasonable timeframe" too, which "usually" means the host's clock is wrong: the code alone does not tell the two
105
+ * apart, so the answer's `Date` does (`googleTokenClockSkewLimitMs`).
106
+ */
107
+ const googleCredentialErrors = new Set(['invalid_grant', 'invalid_client', 'unauthorized_client', 'disabled_client', 'deleted_client']);
108
+
109
+ /**
110
+ * How far Google's clock (the token endpoint's `Date`) and the host's may be apart before an `invalid_grant` is the
111
+ * host's clock and not the credential. Google documents no number for the assertion's `iat` (its service-account guide,
112
+ * read 2026-11-14, asks for "a reasonable timeframe" and "a clock with skew"), so this exceeds no documented tolerance.
113
+ */
114
+ export const googleTokenClockSkewLimitMs = 60_000;
115
+
116
+ /**
117
+ * Google's clock minus the host's, in milliseconds: the answer's `Date` against the host's clock when the answer came.
118
+ * None when the answer has no `Date` or one that does not parse. Only ever compared, never signed: the assertion's `iat`
119
+ * is the host's clock.
120
+ */
121
+ export const googleClockSkewMs = (dateArg: string | undefined, nowArg: number): number | undefined => {
122
+ if (dateArg === undefined) return undefined;
123
+ const date = Date.parse(dateArg);
124
+ return Number.isFinite(date) ? Math.round(date - nowArg) : undefined;
125
+ };
126
+
127
+ /**
128
+ * What a token endpoint answer that is no access token means: an error that names the credential refuses it; any other
129
+ * refusal (none named, or one about the request, its scope or a policy) is the service's, sent again later. An
130
+ * `invalid_grant` while Google's clock and the host's are more than `googleTokenClockSkewLimitMs` apart (`clockSkewArg`,
131
+ * `googleClockSkewMs`) is the host's clock: `service_failed` with the skew, sent again later, never a stored refusal.
132
+ */
133
+ export const googleTokenResult = (statusArg: number, bodyArg: Buffer, retryAfterArg?: number, clockSkewArg?: number): TPushSendResult => {
134
+ let error: unknown;
135
+ try { error = (JSON.parse(bodyArg.toString('utf8')) as { error?: unknown })?.error; } catch { /* judged by the status */ }
136
+ const vendorReason = isPushVendorReason(error) ? { vendorReason: error } : {};
137
+ const retry = retryAfterArg === undefined ? {} : { retryAfterMs: retryAfterArg };
138
+ if (statusArg === 429) return { outcome: 'rate_limited', ...vendorReason, ...retry };
139
+ if (statusArg >= 400 && statusArg < 500 && typeof error === 'string' && googleCredentialErrors.has(error)) {
140
+ if (error === 'invalid_grant' && clockSkewArg !== undefined && Math.abs(clockSkewArg) > googleTokenClockSkewLimitMs) {
141
+ return { outcome: 'service_failed', ...vendorReason, ...retry, clockSkewMs: clockSkewArg };
142
+ }
143
+ return { outcome: 'credential_refused', ...vendorReason };
144
+ }
145
+ return { outcome: 'service_failed', ...vendorReason, ...retry };
146
+ };
147
+
148
+ type TAnswer = { status: number; headers: plugins.http.IncomingHttpHeaders; body: Buffer } | { failed: 'unreachable' };
149
+
150
+ export interface IFcmClientOptions {
151
+ credential: IFcmCredential;
152
+ /** Where the requests connect; Google's hosts when absent. For tests. */
153
+ endpoints?: IPushEndpoints;
154
+ now?: () => number;
155
+ }
156
+
157
+ /**
158
+ * One FCM credential's sender: an access token held until five minutes before it expires (one token request at a time),
159
+ * asked anew once when FCM refuses it, and keep-alive connections that `close` ends.
160
+ */
161
+ export class FcmClient implements IPushSender {
162
+ private accessToken?: { value: string; expiresAt: number };
163
+ private pendingAccessToken?: Promise<{ value: string } | TPushSendResult>;
164
+ private httpsAgent?: plugins.https.Agent;
165
+ private httpAgent?: plugins.http.Agent;
166
+ private readonly requests = new Set<plugins.http.ClientRequest>();
167
+ private closed = false;
168
+
169
+ constructor(private readonly options: IFcmClientOptions) {}
170
+
171
+ private now(): number {
172
+ return this.options.now?.() ?? Date.now();
173
+ }
174
+
175
+ public async send(targetArg: IPushSendTarget, payloadArg: TDevicePushData, expiresAtArg: number, signalArg: AbortSignal): Promise<TPushSendResult> {
176
+ if (this.closed || signalArg.aborted) return { outcome: 'unreachable' };
177
+ const message = fcmMessage(targetArg.token, payloadArg, expiresAtArg, this.now());
178
+ if (!message) return { outcome: 'refused' };
179
+ const body = Buffer.from(JSON.stringify(message), 'utf8');
180
+ const path = `/v1/projects/${encodeURIComponent(this.options.credential.projectId)}/messages:send`;
181
+ let refreshed = false;
182
+ for (;;) {
183
+ const access = await this.currentAccessToken(signalArg);
184
+ if (!('value' in access)) return access;
185
+ const answer = await this.request(googleHosts.fcm, path, {
186
+ authorization: `Bearer ${access.value}`, 'content-type': 'application/json; charset=utf-8',
187
+ }, body, signalArg);
188
+ if ('failed' in answer) return { outcome: answer.failed };
189
+ const error = answer.status >= 200 && answer.status < 300 ? {} : readGoogleError(answer.body);
190
+ // FCM refused the access token itself: it is asked anew once.
191
+ if (answer.status === 401 && error.errorCode === undefined && !refreshed) {
192
+ refreshed = true;
193
+ if (this.accessToken?.value === access.value) this.accessToken = undefined;
194
+ continue;
195
+ }
196
+ return fcmResult(answer.status, error, retryAfterMs(answer.headers['retry-after'], this.now()));
197
+ }
198
+ }
199
+
200
+ /** Ends every connection; a request still running ends as unreachable. */
201
+ public async close(): Promise<void> {
202
+ this.closed = true;
203
+ for (const request of this.requests) request.destroy();
204
+ this.requests.clear();
205
+ this.httpsAgent?.destroy();
206
+ this.httpAgent?.destroy();
207
+ this.httpsAgent = undefined;
208
+ this.httpAgent = undefined;
209
+ this.accessToken = undefined;
210
+ }
211
+
212
+ /** The held access token, or a new one: one token request at a time, shared by every send waiting for it. */
213
+ private currentAccessToken(signalArg: AbortSignal): Promise<{ value: string } | TPushSendResult> {
214
+ if (this.accessToken && this.now() < this.accessToken.expiresAt) return Promise.resolve({ value: this.accessToken.value });
215
+ this.pendingAccessToken ??= this.requestAccessToken(signalArg).finally(() => { this.pendingAccessToken = undefined; });
216
+ return this.pendingAccessToken;
217
+ }
218
+
219
+ /** Signs the service account's assertion and trades it at Google's token endpoint. */
220
+ private async requestAccessToken(signalArg: AbortSignal): Promise<{ value: string } | TPushSendResult> {
221
+ const { clientEmail, privateKeyId, key } = this.options.credential;
222
+ const now = this.now();
223
+ const iat = Math.floor(now / 1000);
224
+ const encode = (valueArg: object) => Buffer.from(JSON.stringify(valueArg), 'utf8').toString('base64url');
225
+ const input = `${encode({ alg: 'RS256', typ: 'JWT', ...(privateKeyId === undefined ? {} : { kid: privateKeyId }) })}.`
226
+ + encode({ iss: clientEmail, scope: fcmScope, aud: googleTokenAudience, iat, exp: iat + 3600 });
227
+ const assertion = `${input}.${plugins.crypto.sign('sha256', Buffer.from(input, 'utf8'), key).toString('base64url')}`;
228
+ const body = Buffer.from(new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString(), 'utf8');
229
+ const answer = await this.request(googleHosts.token, '/token', { 'content-type': 'application/x-www-form-urlencoded' }, body, signalArg);
230
+ if ('failed' in answer) return { outcome: answer.failed };
231
+ if (answer.status !== 200) {
232
+ const answeredAt = this.now();
233
+ return googleTokenResult(answer.status, answer.body, retryAfterMs(answer.headers['retry-after'], answeredAt),
234
+ googleClockSkewMs(answer.headers.date, answeredAt));
235
+ }
236
+ let token: unknown;
237
+ let expiresIn: unknown;
238
+ try {
239
+ ({ access_token: token, expires_in: expiresIn } = JSON.parse(answer.body.toString('utf8')) as Record<string, unknown>);
240
+ } catch { /* refused below */ }
241
+ if (typeof token !== 'string' || !/^[\x21-\x7e]{1,4096}$/u.test(token)
242
+ || !Number.isSafeInteger(expiresIn) || (expiresIn as number) < 1 || (expiresIn as number) > 86_400) {
243
+ return { outcome: 'service_failed' };
244
+ }
245
+ const lifetimeMs = (expiresIn as number) * 1000;
246
+ this.accessToken = { value: token, expiresAt: now + Math.max(lifetimeMs - accessTokenMarginMs, lifetimeMs / 2) };
247
+ return { value: token };
248
+ }
249
+
250
+ /** One `POST` to a pinned Google host, its answer read up to 64 KiB, within the request timeout. */
251
+ private request(hostArg: TGoogleHost, pathArg: string, headersArg: Record<string, string>, bodyArg: Buffer, signalArg: AbortSignal): Promise<TAnswer> {
252
+ if (this.closed || signalArg.aborted) return Promise.resolve({ failed: 'unreachable' });
253
+ const endpoint = (this.options.endpoints ?? pushServiceEndpoints).google(hostArg);
254
+ const secure = endpoint.protocol === 'https:';
255
+ const agent = secure ? (this.httpsAgent ??= new plugins.https.Agent({ keepAlive: true, maxSockets: 4 }))
256
+ : (this.httpAgent ??= new plugins.http.Agent({ keepAlive: true, maxSockets: 4 }));
257
+ return new Promise<TAnswer>((resolve) => {
258
+ let settled = false;
259
+ const finish = (answerArg: TAnswer): void => {
260
+ if (settled) return;
261
+ settled = true;
262
+ clearTimeout(timer);
263
+ signalArg.removeEventListener('abort', abort);
264
+ this.requests.delete(request);
265
+ if ('failed' in answerArg) request.destroy();
266
+ resolve(answerArg);
267
+ };
268
+ const abort = (): void => finish({ failed: 'unreachable' });
269
+ const options = {
270
+ protocol: endpoint.protocol, hostname: endpoint.hostname, port: endpoint.port, method: 'POST', path: pathArg, agent,
271
+ headers: { host: hostArg, 'content-length': String(bodyArg.byteLength), ...headersArg },
272
+ ...(secure ? { servername: hostArg } : {}),
273
+ };
274
+ const request = secure ? plugins.https.request(options) : plugins.http.request(options);
275
+ this.requests.add(request);
276
+ const timer = setTimeout(abort, pushRequestTimeoutMs);
277
+ signalArg.addEventListener('abort', abort, { once: true });
278
+ request.on('error', abort);
279
+ request.on('response', (responseArg) => {
280
+ const chunks: Buffer[] = [];
281
+ let size = 0;
282
+ responseArg.on('data', (chunkArg: Buffer) => {
283
+ size += chunkArg.byteLength;
284
+ if (size <= maximumAnswerBytes) chunks.push(chunkArg);
285
+ });
286
+ responseArg.on('error', abort);
287
+ responseArg.on('end', () => finish({ status: responseArg.statusCode ?? 0, headers: responseArg.headers, body: Buffer.concat(chunks) }));
288
+ });
289
+ request.end(bodyArg);
290
+ });
291
+ }
292
+ }