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,244 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { TDevicePushEnvironment, TDevicePushPlatform } from '../ts_interfaces/devices.js';
3
+
4
+ /**
5
+ * A paired device's registration for notifications (AGL-1639): one document per device, its id the device's. It is
6
+ * its own collection, never a field of the device record, which is exact: an earlier release would refuse a device
7
+ * record that carried one. The token is secret-like: it leaves the controller only to its push service, never in an
8
+ * answer, event, audit entry or log.
9
+ */
10
+ export interface IControllerPushRegistrationDocument {
11
+ /** The device's id. */
12
+ id: string;
13
+ platform: TDevicePushPlatform;
14
+ /** APNs only: the environment the token belongs to. */
15
+ environment?: TDevicePushEnvironment;
16
+ /** The push service's token for the device. */
17
+ token: string;
18
+ /** Whether the device asked for direct report results too. */
19
+ reports: boolean;
20
+ /**
21
+ * 32 random bytes, base64url: the key a notification's collapse key is derived under (HMAC over the item's id). It is
22
+ * made with the registration and kept while it stands, also when the device registers again with another token, so
23
+ * a notification's key stays the same across the host's restarts and the app's registrations.
24
+ */
25
+ salt: string;
26
+ /** Unix milliseconds the registration's platform, token or choices were last set. */
27
+ registeredAt: number;
28
+ }
29
+
30
+ /** What a registration says without its token or salt. */
31
+ export type TControllerPushRegistrationState = Pick<IControllerPushRegistrationDocument, 'platform' | 'reports'>;
32
+
33
+ /** What a device registers: the registration without its id, salt and time. */
34
+ export type TControllerPushRegistrationRequest = Pick<IControllerPushRegistrationDocument, 'platform' | 'environment' | 'token' | 'reports'>;
35
+
36
+ const deviceIdPattern = /^[A-Za-z0-9_-]{24}$/u;
37
+ const saltPattern = /^[A-Za-z0-9_-]{43}$/u;
38
+ const pushEnvironments: readonly unknown[] = ['sandbox', 'production'] satisfies readonly TDevicePushEnvironment[];
39
+
40
+ /**
41
+ * A push token as its platform hands it to the app: an APNs device token as lowercase hex of 32 to 100 bytes (Apple
42
+ * states no fixed size), an FCM registration token as 1 to 1024 characters of letters, digits, `_`, `-` and `:`.
43
+ */
44
+ export const isDevicePushToken = (platformArg: TDevicePushPlatform, valueArg: unknown): valueArg is string => (
45
+ typeof valueArg === 'string' && (platformArg === 'apns'
46
+ ? /^(?:[0-9a-f]{2}){32,100}$/u.test(valueArg)
47
+ : /^[A-Za-z0-9_:-]{1,1024}$/u.test(valueArg))
48
+ );
49
+
50
+ /**
51
+ * A stored token as the record holds it: 1 to 4096 characters without a control character. Never the request's token
52
+ * pattern (`isDevicePushToken`), which guesses at the push services' alphabets: a token a later release took outside
53
+ * it must never make this one refuse the record, which would stop the start's sweep.
54
+ */
55
+ const isStoredPushToken = (valueArg: unknown): valueArg is string => (
56
+ typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= 4096 && !/\p{Cc}/u.test(valueArg)
57
+ );
58
+
59
+ const isTimestamp = (valueArg: unknown): valueArg is number => Number.isSafeInteger(valueArg) && (valueArg as number) > 0;
60
+
61
+ const assertDocument: (valueArg: unknown) => asserts valueArg is IControllerPushRegistrationDocument = (valueArg) => {
62
+ const value = valueArg as Partial<IControllerPushRegistrationDocument> | null;
63
+ const keys = value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value) : [];
64
+ const expected = ['id', 'platform', 'token', 'reports', 'salt', 'registeredAt', ...(value?.platform === 'apns' ? ['environment'] : [])];
65
+ if (
66
+ !value
67
+ || keys.length !== expected.length
68
+ || !expected.every((keyArg) => Object.hasOwn(value, keyArg))
69
+ || typeof value.id !== 'string' || !deviceIdPattern.test(value.id)
70
+ || (value.platform !== 'apns' && value.platform !== 'fcm')
71
+ || (value.platform === 'apns' && !pushEnvironments.includes(value.environment))
72
+ || !isStoredPushToken(value.token)
73
+ || typeof value.reports !== 'boolean'
74
+ || typeof value.salt !== 'string' || !saltPattern.test(value.salt)
75
+ || !isTimestamp(value.registeredAt)
76
+ ) {
77
+ // Never the value: the document holds a token.
78
+ throw new Error('Invalid push registration record.');
79
+ }
80
+ };
81
+
82
+ @plugins.nosqldb.managed({ collectionName: 'agl_controller_push_registrations' })
83
+ @plugins.nosqldb.exactPersistence({ assertDocument })
84
+ export class ControllerPushRegistrationModel extends plugins.nosqldb.SmartDataDbDoc<
85
+ ControllerPushRegistrationModel,
86
+ IControllerPushRegistrationDocument
87
+ > {
88
+ declare static exact: plugins.nosqldb.TExact<ControllerPushRegistrationModel>;
89
+ @plugins.nosqldb.unI() public id!: string;
90
+ @plugins.nosqldb.svDb() public platform!: TDevicePushPlatform;
91
+ @plugins.nosqldb.svDb() public environment?: TDevicePushEnvironment;
92
+ @plugins.nosqldb.svDb() public token!: string;
93
+ @plugins.nosqldb.svDb() public reports!: boolean;
94
+ @plugins.nosqldb.svDb() public salt!: string;
95
+ @plugins.nosqldb.svDb() public registeredAt!: number;
96
+ }
97
+
98
+ const stateOf = (documentArg: IControllerPushRegistrationDocument): TControllerPushRegistrationState => ({
99
+ platform: documentArg.platform,
100
+ reports: documentArg.reports,
101
+ });
102
+
103
+ /** A device's registration, without its token or salt; none while it holds none. */
104
+ export const readPushRegistration = async (deviceIdArg: string): Promise<TControllerPushRegistrationState | undefined> => {
105
+ const stored = await ControllerPushRegistrationModel.exact.findStoredOne({ id: deviceIdArg });
106
+ return stored === null ? undefined : stateOf(ControllerPushRegistrationModel.exact.toPersisted(stored));
107
+ };
108
+
109
+ /**
110
+ * Sets a device's registration: a new one gets a fresh salt, an existing one takes the request's platform, token and
111
+ * choices and keeps its salt; the same request again writes nothing. The caller runs it after the device's record and
112
+ * in the one order of the device's writes, so a revoked device is never registered again.
113
+ */
114
+ export const writePushRegistration = async (
115
+ deviceIdArg: string,
116
+ requestArg: TControllerPushRegistrationRequest,
117
+ nowArg: number,
118
+ ): Promise<TControllerPushRegistrationState> => {
119
+ const content = {
120
+ platform: requestArg.platform,
121
+ ...(requestArg.platform === 'apns' ? { environment: requestArg.environment } : {}),
122
+ token: requestArg.token,
123
+ reports: requestArg.reports,
124
+ };
125
+ const current = await ControllerPushRegistrationModel.exact.findStoredOne({ id: deviceIdArg });
126
+ if (current === null) {
127
+ const inserted = await ControllerPushRegistrationModel.exact.insert({
128
+ id: deviceIdArg, ...content, salt: plugins.crypto.randomBytes(32).toString('base64url'), registeredAt: nowArg,
129
+ });
130
+ if (inserted.status !== 'inserted') throw new Error('The push registration changed concurrently and was not stored.');
131
+ return stateOf(ControllerPushRegistrationModel.exact.toPersisted(inserted.document));
132
+ }
133
+ const stored = ControllerPushRegistrationModel.exact.toPersisted(current);
134
+ if (stored.platform === content.platform && stored.environment === content.environment && stored.token === content.token
135
+ && stored.reports === content.reports) {
136
+ return stateOf(stored);
137
+ }
138
+ const result = await ControllerPushRegistrationModel.exact.transition({ current, change: (modelArg) => {
139
+ modelArg.platform = content.platform;
140
+ if (content.environment === undefined) delete modelArg.environment;
141
+ else modelArg.environment = content.environment;
142
+ modelArg.token = content.token;
143
+ modelArg.reports = content.reports;
144
+ modelArg.registeredAt = nowArg;
145
+ } });
146
+ if (result.status !== 'transitioned') throw new Error('The push registration changed concurrently and was not stored.');
147
+ return stateOf(ControllerPushRegistrationModel.exact.toPersisted(result.document));
148
+ };
149
+
150
+ /**
151
+ * Deletes a device's registration; answers whether there was one. `optionsArg.session` runs it inside the caller's
152
+ * transaction (a revocation, or an origin move that removes the device).
153
+ */
154
+ export const deletePushRegistration = async (
155
+ deviceIdArg: string,
156
+ optionsArg: plugins.nosqldb.IExactSessionOptions = {},
157
+ ): Promise<boolean> => {
158
+ const current = await ControllerPushRegistrationModel.exact.findStoredOne({ id: deviceIdArg }, optionsArg);
159
+ if (current === null) return false;
160
+ const result = await ControllerPushRegistrationModel.exact.delete({ current }, optionsArg);
161
+ if (result.status !== 'deleted' && await ControllerPushRegistrationModel.exact.findStoredOne({ id: deviceIdArg }, optionsArg)) {
162
+ throw new Error('A push registration could not be removed.');
163
+ }
164
+ return true;
165
+ };
166
+
167
+ /**
168
+ * Deletes every registration whose device is gone: one left behind by a write that failed half-way or by an earlier
169
+ * release that revoked a device without knowing registrations. Answers how many it deleted.
170
+ */
171
+ export const sweepPushRegistrations = async (pairedArg: (deviceIdArg: string) => Promise<boolean>): Promise<number> => {
172
+ let deleted = 0;
173
+ for (const current of await ControllerPushRegistrationModel.exact.findStored()) {
174
+ const { id } = ControllerPushRegistrationModel.exact.toPersisted(current);
175
+ if (await pairedArg(id)) continue;
176
+ const result = await ControllerPushRegistrationModel.exact.delete({ current });
177
+ if (result.status === 'deleted') deleted += 1;
178
+ else if (await ControllerPushRegistrationModel.exact.findStoredOne({ id })) {
179
+ throw new Error('A push registration of a removed device could not be removed.');
180
+ }
181
+ }
182
+ return deleted;
183
+ };
184
+
185
+ /** How many of `deviceIdsArg` hold a registration, per platform (`agl push status`). */
186
+ export const countPushRegistrations = async (deviceIdsArg: ReadonlySet<string>): Promise<Record<TDevicePushPlatform, number>> => {
187
+ const counts: Record<TDevicePushPlatform, number> = { apns: 0, fcm: 0 };
188
+ for (const current of await ControllerPushRegistrationModel.exact.findStored()) {
189
+ const { id, platform } = ControllerPushRegistrationModel.exact.toPersisted(current);
190
+ if (deviceIdsArg.has(id)) counts[platform] += 1;
191
+ }
192
+ return counts;
193
+ };
194
+
195
+ /** A registration as the delivery sends to it, with its token: it never leaves the host but to its push service. */
196
+ export interface IControllerPushTarget {
197
+ deviceId: string;
198
+ platform: TDevicePushPlatform;
199
+ environment?: TDevicePushEnvironment;
200
+ token: string;
201
+ /** Whether the device asked for direct report results too. */
202
+ reports: boolean;
203
+ /** The key a notification's key is made under (`pushNotificationKey`). */
204
+ salt: string;
205
+ }
206
+
207
+ /** The registrations of `deviceIdsArg`, with their tokens, in the order of the ids. */
208
+ export const readPushTargets = async (deviceIdsArg: readonly string[]): Promise<IControllerPushTarget[]> => {
209
+ const targets: IControllerPushTarget[] = [];
210
+ for (const deviceId of deviceIdsArg) {
211
+ const stored = await ControllerPushRegistrationModel.exact.findStoredOne({ id: deviceId });
212
+ if (stored === null) continue;
213
+ const { platform, environment, token, reports, salt } = ControllerPushRegistrationModel.exact.toPersisted(stored);
214
+ targets.push({ deviceId, platform, ...(environment === undefined ? {} : { environment }), token, reports, salt });
215
+ }
216
+ return targets;
217
+ };
218
+
219
+ /**
220
+ * Deletes a device's registration if it still holds `tokenArg`: its push service called that token gone. A registration
221
+ * the device renewed with another token meanwhile stays. Answers whether it deleted one.
222
+ */
223
+ export const deletePushRegistrationHolding = async (deviceIdArg: string, tokenArg: string): Promise<boolean> => {
224
+ const current = await ControllerPushRegistrationModel.exact.findStoredOne({ id: deviceIdArg });
225
+ if (current === null || ControllerPushRegistrationModel.exact.toPersisted(current).token !== tokenArg) return false;
226
+ const result = await ControllerPushRegistrationModel.exact.delete({ current });
227
+ return result.status === 'deleted';
228
+ };
229
+
230
+ /**
231
+ * What a notification's key is made over besides an Inbox item's id: never an item's id, which holds no control
232
+ * character, so the key of the owner's test notification, of the summary and of a direct report's result never equals
233
+ * an item's. A report's key is over its name: a newer result of the same report replaces the older one.
234
+ */
235
+ export const pushKeySubjects = {
236
+ test: '\u0000test',
237
+ summary: '\u0000summary',
238
+ report: (nameArg: string): string => `\u0000report\u0000${nameArg}`,
239
+ } as const;
240
+
241
+ /** A notification's key: base64url of HMAC-SHA256 under the registration's salt over `subjectArg` (an item's id). */
242
+ export const pushNotificationKey = (saltArg: string, subjectArg: string): string => (
243
+ plugins.crypto.createHmac('sha256', Buffer.from(saltArg, 'base64url')).update(subjectArg, 'utf8').digest('base64url')
244
+ );
@@ -0,0 +1,428 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { ITpmSecretCodec } from './classes.tpmsecretcodec.js';
3
+ import { isPushVendorReason } from './interfaces.push.js';
4
+ import type { TDevicePushPlatform } from '../ts_interfaces/devices.js';
5
+ import type { IPushApnsStatus, IPushFcmStatus, TPushCredentialState } from '../ts_interfaces/push.js';
6
+ import {
7
+ isApnsSigningKey,
8
+ isAppleId,
9
+ isBundleId,
10
+ isFirebaseProjectId,
11
+ isServiceAccountEmail,
12
+ isServiceAccountKeyId,
13
+ isServiceAccountSigningKey,
14
+ privateKeyBytes,
15
+ privateKeyFromBytes,
16
+ type IApnsCredentialInput,
17
+ type IFcmCredentialInput,
18
+ } from './functions.pushcredentials.js';
19
+
20
+ /**
21
+ * The host's push settings (AGL-1639): one document per controller in `agl_controller_push_settings`, `{ id, content }`.
22
+ * The top level is fixed for good (the exact client refuses a stored top-level field its model does not declare);
23
+ * `content` is a plain object this release reads key by key and writes back with every key it does not know, so a
24
+ * document a later release wrote keeps what that release added. This release reads `previews` (off unless true), and
25
+ * `apns` and `fcm`: what the credential is for, its key TPM2-sealed (`TpmSecretCodec`) under a name bound to the
26
+ * controller, the platform and the credential's generation, when it was set, and `refused` once Apple or Google
27
+ * refused it. The running controller is the only writer: `agl push` reaches it over its private channel.
28
+ */
29
+ export interface IControllerPushSettingsDocument {
30
+ /** `controller:<port>`. */
31
+ id: string;
32
+ content: Record<string, unknown>;
33
+ }
34
+
35
+ /** A key as the store holds it: sealed, with the generation its seal name binds. */
36
+ export interface IStoredPushKey {
37
+ generation: number;
38
+ ciphertext: string;
39
+ }
40
+
41
+ /** Apple or Google refused the credential: nothing is sent on the platform until the owner sets it again. */
42
+ export interface IStoredPushRefusal {
43
+ at: number;
44
+ /** The push service's code for the refusal, when it named one. */
45
+ vendorReason?: string;
46
+ }
47
+
48
+ interface IStoredApnsCredential {
49
+ keyId: string;
50
+ teamId: string;
51
+ topic: string;
52
+ key: IStoredPushKey;
53
+ setAt: number;
54
+ refused?: IStoredPushRefusal;
55
+ }
56
+
57
+ interface IStoredFcmCredential {
58
+ projectId: string;
59
+ clientEmail: string;
60
+ privateKeyId?: string;
61
+ key: IStoredPushKey;
62
+ setAt: number;
63
+ refused?: IStoredPushRefusal;
64
+ }
65
+
66
+ /** The stored document's `content` is bounded plain JSON. */
67
+ const maximumContentBytes = 64 * 1024;
68
+
69
+ const isPlainObject = (valueArg: unknown): valueArg is Record<string, unknown> => (
70
+ !!valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg)
71
+ && (Object.getPrototypeOf(valueArg) === Object.prototype || Object.getPrototypeOf(valueArg) === null)
72
+ );
73
+
74
+ const assertDocument: (valueArg: unknown) => asserts valueArg is IControllerPushSettingsDocument = (valueArg) => {
75
+ const value = valueArg as Partial<IControllerPushSettingsDocument> | null;
76
+ let size = Number.POSITIVE_INFINITY;
77
+ try { size = Buffer.byteLength(JSON.stringify(value?.content), 'utf8'); } catch { /* refused below */ }
78
+ if (!isPlainObject(value)
79
+ || Object.keys(value).length !== 2
80
+ || typeof value.id !== 'string' || !/^controller:[1-9][0-9]{0,4}$/u.test(value.id)
81
+ || !isPlainObject(value.content)
82
+ || size > maximumContentBytes) {
83
+ throw new Error('Invalid push settings record.');
84
+ }
85
+ };
86
+
87
+ @plugins.nosqldb.managed({ collectionName: 'agl_controller_push_settings' })
88
+ @plugins.nosqldb.exactPersistence({ assertDocument })
89
+ export class ControllerPushSettingsModel extends plugins.nosqldb.SmartDataDbDoc<ControllerPushSettingsModel, IControllerPushSettingsDocument> {
90
+ declare static exact: plugins.nosqldb.TExact<ControllerPushSettingsModel>;
91
+ @plugins.nosqldb.unI() public id!: string;
92
+ @plugins.nosqldb.svDb() public content!: Record<string, unknown>;
93
+ }
94
+
95
+ const isTime = (valueArg: unknown): valueArg is number => Number.isSafeInteger(valueArg) && (valueArg as number) > 0;
96
+
97
+ const isStoredKey = (valueArg: unknown): valueArg is IStoredPushKey => (
98
+ isPlainObject(valueArg)
99
+ && Number.isSafeInteger(valueArg.generation) && (valueArg.generation as number) >= 1
100
+ && typeof valueArg.ciphertext === 'string' && /^[A-Za-z0-9_-]{1,131072}$/u.test(valueArg.ciphertext)
101
+ );
102
+
103
+ const isRefusal = (valueArg: unknown): valueArg is IStoredPushRefusal => (
104
+ isPlainObject(valueArg) && isTime(valueArg.at) && (valueArg.vendorReason === undefined || isPushVendorReason(valueArg.vendorReason))
105
+ );
106
+
107
+ /** A stored entry this release reads: its own keys checked, any other key a later release's. */
108
+ const readApnsEntry = (valueArg: unknown): IStoredApnsCredential | undefined => (
109
+ isPlainObject(valueArg) && isAppleId(valueArg.keyId) && isAppleId(valueArg.teamId) && isBundleId(valueArg.topic)
110
+ && isStoredKey(valueArg.key) && isTime(valueArg.setAt) && (valueArg.refused === undefined || isRefusal(valueArg.refused))
111
+ ? valueArg as unknown as IStoredApnsCredential : undefined
112
+ );
113
+
114
+ const readFcmEntry = (valueArg: unknown): IStoredFcmCredential | undefined => (
115
+ isPlainObject(valueArg) && isFirebaseProjectId(valueArg.projectId) && isServiceAccountEmail(valueArg.clientEmail)
116
+ && (valueArg.privateKeyId === undefined || isServiceAccountKeyId(valueArg.privateKeyId))
117
+ && isStoredKey(valueArg.key) && isTime(valueArg.setAt) && (valueArg.refused === undefined || isRefusal(valueArg.refused))
118
+ ? valueArg as unknown as IStoredFcmCredential : undefined
119
+ );
120
+
121
+ /** The APNs credential a sender signs with. */
122
+ export interface IApnsCredential {
123
+ keyId: string;
124
+ teamId: string;
125
+ topic: string;
126
+ key: plugins.crypto.KeyObject;
127
+ /** The stored generation: a refusal names it, so a credential set meanwhile is not the one refused. */
128
+ generation: number;
129
+ }
130
+
131
+ /** The FCM credential a sender signs with. */
132
+ export interface IFcmCredential {
133
+ projectId: string;
134
+ clientEmail: string;
135
+ privateKeyId?: string;
136
+ key: plugins.crypto.KeyObject;
137
+ generation: number;
138
+ }
139
+
140
+ interface IHeldPlatform<TStored, TCredential> {
141
+ state: TPushCredentialState;
142
+ stored?: TStored;
143
+ /** Present exactly while `state` is `ready`. */
144
+ credential?: TCredential;
145
+ }
146
+
147
+ export interface IControllerPushSettingsOptions {
148
+ /** `controller:<port>`. */
149
+ controllerId: string;
150
+ /** The controller database's issuer id: a key is sealed under a name bound to it. */
151
+ issuerId: string;
152
+ codec: ITpmSecretCodec;
153
+ now?: () => number;
154
+ }
155
+
156
+ const readRecord = (controllerIdArg: string) => ControllerPushSettingsModel.exact.findStoredOne({ id: controllerIdArg });
157
+
158
+ /**
159
+ * The push settings of one running controller: what it read at start and every change the owner makes, in one order.
160
+ * The keys exist in plaintext only in this process, as key objects; the store holds them sealed. A change of a
161
+ * platform's credential reaches the listeners (the delivery service drops its sender for the platform).
162
+ */
163
+ export class ControllerPushSettings {
164
+ private previewsOn = false;
165
+ private apnsHeld: IHeldPlatform<IStoredApnsCredential, IApnsCredential> = { state: 'unset' };
166
+ private fcmHeld: IHeldPlatform<IStoredFcmCredential, IFcmCredential> = { state: 'unset' };
167
+ /**
168
+ * The newest generation each platform's credential had in this process, also after `unset`: the next one is always
169
+ * higher, so a refusal of an earlier credential that arrives late never names the one set since.
170
+ */
171
+ private readonly generations: Record<TDevicePushPlatform, number> = { apns: 0, fcm: 0 };
172
+ private readonly listeners = new Set<(platformArg: TDevicePushPlatform) => void>();
173
+ private mutationTail: Promise<unknown> = Promise.resolve();
174
+ private closed = false;
175
+
176
+ private constructor(private readonly options: IControllerPushSettingsOptions) {}
177
+
178
+ /** Reads the controller's settings and unseals each credential that was not refused. */
179
+ public static async open(optionsArg: IControllerPushSettingsOptions): Promise<ControllerPushSettings> {
180
+ const settings = new ControllerPushSettings(optionsArg);
181
+ const stored = await readRecord(optionsArg.controllerId);
182
+ const content = stored ? ControllerPushSettingsModel.exact.toPersisted(stored).content : {};
183
+ settings.previewsOn = content.previews === true;
184
+ settings.apnsHeld = await settings.holdApns(content.apns);
185
+ settings.fcmHeld = await settings.holdFcm(content.fcm);
186
+ // An entry this release cannot read still names its generation: the next credential's seal name is not that one's.
187
+ for (const platform of ['apns', 'fcm'] as const) {
188
+ const entry = content[platform];
189
+ const generation = isPlainObject(entry) && isPlainObject(entry.key) ? entry.key.generation : undefined;
190
+ if (Number.isSafeInteger(generation) && (generation as number) > 0) settings.generations[platform] = generation as number;
191
+ }
192
+ return settings;
193
+ }
194
+
195
+ private now(): number {
196
+ return this.options.now?.() ?? Date.now();
197
+ }
198
+
199
+ /** Whether notifications carry previews. */
200
+ public previews(): boolean {
201
+ return this.previewsOn;
202
+ }
203
+
204
+ /** What `agl push status` shows of the APNs credential, without the key. */
205
+ public apnsStatus(): Omit<IPushApnsStatus, 'registrations'> {
206
+ const { state, stored } = this.apnsHeld;
207
+ return {
208
+ state,
209
+ ...(stored === undefined ? {} : { keyId: stored.keyId, teamId: stored.teamId, topic: stored.topic, setAt: stored.setAt }),
210
+ ...(state === 'refused' && stored?.refused ? { refused: { at: stored.refused.at, reason: 'credential_refused' as const,
211
+ ...(stored.refused.vendorReason === undefined ? {} : { vendorReason: stored.refused.vendorReason }) } } : {}),
212
+ };
213
+ }
214
+
215
+ /** What `agl push status` shows of the FCM credential, without the key. */
216
+ public fcmStatus(): Omit<IPushFcmStatus, 'registrations'> {
217
+ const { state, stored } = this.fcmHeld;
218
+ return {
219
+ state,
220
+ ...(stored === undefined ? {} : { projectId: stored.projectId, clientEmail: stored.clientEmail, setAt: stored.setAt }),
221
+ ...(state === 'refused' && stored?.refused ? { refused: { at: stored.refused.at, reason: 'credential_refused' as const,
222
+ ...(stored.refused.vendorReason === undefined ? {} : { vendorReason: stored.refused.vendorReason }) } } : {}),
223
+ };
224
+ }
225
+
226
+ /** The APNs credential to send with, while it is ready. */
227
+ public apnsCredential(): IApnsCredential | undefined {
228
+ return this.closed ? undefined : this.apnsHeld.credential;
229
+ }
230
+
231
+ /** The FCM credential to send with, while it is ready. */
232
+ public fcmCredential(): IFcmCredential | undefined {
233
+ return this.closed ? undefined : this.fcmHeld.credential;
234
+ }
235
+
236
+ /** Whether the host holds a credential for the platform that Apple or Google did not refuse. */
237
+ public ready(platformArg: TDevicePushPlatform): boolean {
238
+ return (platformArg === 'apns' ? this.apnsCredential() : this.fcmCredential()) !== undefined;
239
+ }
240
+
241
+ /** Calls `listenerArg` with the platform whenever its credential changes; answers the unsubscription. */
242
+ public onChange(listenerArg: (platformArg: TDevicePushPlatform) => void): () => void {
243
+ this.listeners.add(listenerArg);
244
+ return () => { this.listeners.delete(listenerArg); };
245
+ }
246
+
247
+ /** Seals and stores a new APNs credential, which replaces the one held (a refused one too). */
248
+ public setApns(inputArg: IApnsCredentialInput): Promise<boolean> {
249
+ return this.mutate(async () => {
250
+ const generation = this.nextGeneration('apns');
251
+ const key = await this.seal('apns', generation, inputArg.key);
252
+ const stored: IStoredApnsCredential = { keyId: inputArg.keyId, teamId: inputArg.teamId, topic: inputArg.topic, key, setAt: this.now() };
253
+ await this.write((contentArg) => { contentArg.apns = stored; });
254
+ this.apnsHeld = { state: 'ready', stored, credential: {
255
+ keyId: stored.keyId, teamId: stored.teamId, topic: stored.topic, key: inputArg.key, generation,
256
+ } };
257
+ this.changed('apns');
258
+ return true;
259
+ });
260
+ }
261
+
262
+ /** Seals and stores a new FCM credential, which replaces the one held (a refused one too). */
263
+ public setFcm(inputArg: IFcmCredentialInput): Promise<boolean> {
264
+ return this.mutate(async () => {
265
+ const generation = this.nextGeneration('fcm');
266
+ const key = await this.seal('fcm', generation, inputArg.key);
267
+ const stored: IStoredFcmCredential = {
268
+ projectId: inputArg.projectId, clientEmail: inputArg.clientEmail,
269
+ ...(inputArg.privateKeyId === undefined ? {} : { privateKeyId: inputArg.privateKeyId }), key, setAt: this.now(),
270
+ };
271
+ await this.write((contentArg) => { contentArg.fcm = stored; });
272
+ this.fcmHeld = { state: 'ready', stored, credential: {
273
+ projectId: stored.projectId, clientEmail: stored.clientEmail,
274
+ ...(stored.privateKeyId === undefined ? {} : { privateKeyId: stored.privateKeyId }), key: inputArg.key, generation,
275
+ } };
276
+ this.changed('fcm');
277
+ return true;
278
+ });
279
+ }
280
+
281
+ /** Removes a platform's credential; answers whether the host held one (also an unreadable one). */
282
+ public unset(platformArg: TDevicePushPlatform): Promise<boolean> {
283
+ return this.mutate(async () => {
284
+ const current = await readRecord(this.options.controllerId);
285
+ const held = platformArg === 'apns' ? this.apnsHeld : this.fcmHeld;
286
+ if (!current || (!Object.hasOwn(ControllerPushSettingsModel.exact.toPersisted(current).content, platformArg) && held.state === 'unset')) {
287
+ return false;
288
+ }
289
+ await this.write((contentArg) => { delete contentArg[platformArg]; });
290
+ if (platformArg === 'apns') this.apnsHeld = { state: 'unset' };
291
+ else this.fcmHeld = { state: 'unset' };
292
+ this.changed(platformArg);
293
+ return true;
294
+ });
295
+ }
296
+
297
+ /** Turns previews on or off; answers whether that changed them. */
298
+ public setPreviews(previewsArg: boolean): Promise<boolean> {
299
+ return this.mutate(async () => {
300
+ if (this.previewsOn === previewsArg) return false;
301
+ await this.write((contentArg) => { contentArg.previews = previewsArg; });
302
+ this.previewsOn = previewsArg;
303
+ return true;
304
+ });
305
+ }
306
+
307
+ /**
308
+ * Apple or Google refused generation `generationArg` of a platform's credential: it is kept as `refused`, and nothing
309
+ * is sent on the platform until the owner sets it again. A credential set since is not the one refused.
310
+ */
311
+ public refuse(platformArg: TDevicePushPlatform, generationArg: number, vendorReasonArg?: string): Promise<boolean> {
312
+ return this.mutate(async () => {
313
+ const held = platformArg === 'apns' ? this.apnsHeld : this.fcmHeld;
314
+ if (held.state !== 'ready' || held.credential?.generation !== generationArg || !held.stored) return false;
315
+ const refused: IStoredPushRefusal = { at: this.now(), ...(isPushVendorReason(vendorReasonArg) ? { vendorReason: vendorReasonArg } : {}) };
316
+ const stored = { ...held.stored, refused };
317
+ await this.write((contentArg) => {
318
+ // What a later release added to the entry stays.
319
+ contentArg[platformArg] = { ...(isPlainObject(contentArg[platformArg]) ? contentArg[platformArg] : {}), ...stored };
320
+ });
321
+ if (platformArg === 'apns') this.apnsHeld = { state: 'refused', stored: stored as IStoredApnsCredential };
322
+ else this.fcmHeld = { state: 'refused', stored: stored as IStoredFcmCredential };
323
+ this.changed(platformArg);
324
+ return true;
325
+ });
326
+ }
327
+
328
+ /** Forgets the keys; the record stays. Changes still running fail. */
329
+ public close(): void {
330
+ this.closed = true;
331
+ this.apnsHeld = { state: this.apnsHeld.state, ...(this.apnsHeld.stored ? { stored: this.apnsHeld.stored } : {}) };
332
+ this.fcmHeld = { state: this.fcmHeld.state, ...(this.fcmHeld.stored ? { stored: this.fcmHeld.stored } : {}) };
333
+ this.listeners.clear();
334
+ }
335
+
336
+ /** A generation the platform's credential never had in this process, nor the stored one. */
337
+ private nextGeneration(platformArg: TDevicePushPlatform): number {
338
+ this.generations[platformArg] += 1;
339
+ return this.generations[platformArg];
340
+ }
341
+
342
+ private changed(platformArg: TDevicePushPlatform): void {
343
+ for (const listener of [...this.listeners]) listener(platformArg);
344
+ }
345
+
346
+ private sealName(platformArg: TDevicePushPlatform, generationArg: number): string {
347
+ return `agl-controller.${this.options.issuerId.slice(0, 22)}.${this.options.controllerId.replace(':', '-')}.push-${platformArg}.${generationArg}`;
348
+ }
349
+
350
+ private async seal(platformArg: TDevicePushPlatform, generationArg: number, keyArg: plugins.crypto.KeyObject): Promise<IStoredPushKey> {
351
+ const bytes = privateKeyBytes(keyArg);
352
+ try {
353
+ return { generation: generationArg, ciphertext: await this.options.codec.seal(this.sealName(platformArg, generationArg), bytes) };
354
+ } finally {
355
+ bytes.fill(0);
356
+ }
357
+ }
358
+
359
+ /** The key of a stored credential, unsealed; none (`unreadable`) when this machine cannot unseal it. */
360
+ private async unseal(platformArg: TDevicePushPlatform, keyArg: IStoredPushKey): Promise<plugins.crypto.KeyObject | undefined> {
361
+ let bytes: Uint8Array | undefined;
362
+ try {
363
+ bytes = await this.options.codec.unseal(this.sealName(platformArg, keyArg.generation), keyArg.ciphertext);
364
+ return privateKeyFromBytes(bytes);
365
+ } catch {
366
+ return undefined;
367
+ } finally {
368
+ bytes?.fill(0);
369
+ }
370
+ }
371
+
372
+ private async holdApns(valueArg: unknown): Promise<IHeldPlatform<IStoredApnsCredential, IApnsCredential>> {
373
+ if (valueArg === undefined) return { state: 'unset' };
374
+ const stored = readApnsEntry(valueArg);
375
+ if (!stored) return this.unreadable('APNs', 'apns');
376
+ if (stored.refused) return { state: 'refused', stored };
377
+ const key = await this.unseal('apns', stored.key);
378
+ if (!key || !isApnsSigningKey(key)) return { ...this.unreadable('APNs', 'apns'), stored };
379
+ return { state: 'ready', stored, credential: {
380
+ keyId: stored.keyId, teamId: stored.teamId, topic: stored.topic, key, generation: stored.key.generation,
381
+ } };
382
+ }
383
+
384
+ private async holdFcm(valueArg: unknown): Promise<IHeldPlatform<IStoredFcmCredential, IFcmCredential>> {
385
+ if (valueArg === undefined) return { state: 'unset' };
386
+ const stored = readFcmEntry(valueArg);
387
+ if (!stored) return this.unreadable('FCM', 'fcm');
388
+ if (stored.refused) return { state: 'refused', stored };
389
+ const key = await this.unseal('fcm', stored.key);
390
+ if (!key || !isServiceAccountSigningKey(key)) return { ...this.unreadable('FCM', 'fcm'), stored };
391
+ return { state: 'ready', stored, credential: {
392
+ projectId: stored.projectId, clientEmail: stored.clientEmail,
393
+ ...(stored.privateKeyId === undefined ? {} : { privateKeyId: stored.privateKeyId }), key, generation: stored.key.generation,
394
+ } };
395
+ }
396
+
397
+ private unreadable(nameArg: string, platformArg: TDevicePushPlatform): { state: 'unreadable' } {
398
+ console.warn(`The ${nameArg} push credential of ${this.options.controllerId} cannot be read or unsealed on this machine, so `
399
+ + `nothing is sent on it: set it again with \`agl push ${platformArg} set\`.`);
400
+ return { state: 'unreadable' };
401
+ }
402
+
403
+ /** Changes the stored `content` with `changeArg`, keeping every key this release does not know. */
404
+ private async write(changeArg: (contentArg: Record<string, unknown>) => void): Promise<void> {
405
+ const current = await readRecord(this.options.controllerId);
406
+ if (!current) {
407
+ const content: Record<string, unknown> = {};
408
+ changeArg(content);
409
+ const inserted = await ControllerPushSettingsModel.exact.insert({ id: this.options.controllerId, content });
410
+ if (inserted.status !== 'inserted') throw new Error('The push settings changed concurrently and were not stored.');
411
+ return;
412
+ }
413
+ const content = structuredClone(ControllerPushSettingsModel.exact.toPersisted(current).content);
414
+ changeArg(content);
415
+ const result = await ControllerPushSettingsModel.exact.transition({ current, change: (modelArg) => { modelArg.content = content; } });
416
+ if (result.status !== 'transitioned') throw new Error('The push settings changed concurrently and were not stored.');
417
+ }
418
+
419
+ private mutate<T>(operationArg: () => Promise<T>): Promise<T> {
420
+ if (this.closed) return Promise.reject(new Error('The push settings are closed.'));
421
+ const task = this.mutationTail.then(() => {
422
+ if (this.closed) throw new Error('The push settings are closed.');
423
+ return operationArg();
424
+ });
425
+ this.mutationTail = task.then(() => undefined, () => undefined);
426
+ return task;
427
+ }
428
+ }