agl 43.7.0 → 43.9.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 (143) hide show
  1. package/changelog.md +33 -0
  2. package/dist_serve/bundle.js +871 -858
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/aglapisurface.document.js +824 -6
  6. package/dist_ts/aglapi/interfaces.d.ts +43 -0
  7. package/dist_ts/aglapi/interfaces.js +11 -1
  8. package/dist_ts/classes.apnsclient.d.ts +97 -0
  9. package/dist_ts/classes.apnsclient.js +363 -0
  10. package/dist_ts/classes.authmodels.js +19 -6
  11. package/dist_ts/classes.authstore.js +15 -2
  12. package/dist_ts/classes.cli.js +8 -1
  13. package/dist_ts/classes.controller.d.ts +30 -3
  14. package/dist_ts/classes.controller.js +250 -9
  15. package/dist_ts/classes.controllerdevices.d.ts +35 -7
  16. package/dist_ts/classes.controllerdevices.js +86 -13
  17. package/dist_ts/classes.controllerpush.d.ts +111 -0
  18. package/dist_ts/classes.controllerpush.js +299 -0
  19. package/dist_ts/classes.fcmclient.d.ts +78 -0
  20. package/dist_ts/classes.fcmclient.js +278 -0
  21. package/dist_ts/classes.inbox.d.ts +10 -2
  22. package/dist_ts/classes.inbox.js +9 -2
  23. package/dist_ts/classes.mcpclient.d.ts +5 -0
  24. package/dist_ts/classes.mcpclient.js +20 -8
  25. package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
  26. package/dist_ts/classes.mcpcontrollerhost.js +21 -2
  27. package/dist_ts/classes.mcptools.d.ts +1 -1
  28. package/dist_ts/classes.mcptools.js +2 -1
  29. package/dist_ts/classes.mcpvalidation.js +4 -1
  30. package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
  31. package/dist_ts/classes.mcpworkercaller.js +26 -4
  32. package/dist_ts/classes.pushdelivery.d.ts +115 -0
  33. package/dist_ts/classes.pushdelivery.js +311 -0
  34. package/dist_ts/classes.pushhandover.d.ts +46 -0
  35. package/dist_ts/classes.pushhandover.js +131 -0
  36. package/dist_ts/classes.pushregistrations.d.ts +96 -0
  37. package/dist_ts/classes.pushregistrations.js +263 -0
  38. package/dist_ts/classes.pushsettings.d.ts +125 -0
  39. package/dist_ts/classes.pushsettings.js +377 -0
  40. package/dist_ts/classes.ticketstore.d.ts +3 -3
  41. package/dist_ts/classes.ticketstore.js +23 -4
  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 +43 -3
  52. package/dist_ts/functions.mcptickettools.d.ts +60 -0
  53. package/dist_ts/functions.mcptickettools.js +4 -3
  54. package/dist_ts/functions.pushcli.d.ts +43 -0
  55. package/dist_ts/functions.pushcli.js +201 -0
  56. package/dist_ts/functions.pushcredentials.d.ts +53 -0
  57. package/dist_ts/functions.pushcredentials.js +111 -0
  58. package/dist_ts/functions.pushwire.d.ts +8 -0
  59. package/dist_ts/functions.pushwire.js +83 -0
  60. package/dist_ts/functions.remotecli.d.ts +2 -2
  61. package/dist_ts/functions.remotecli.js +4 -4
  62. package/dist_ts/functions.ticketcli.d.ts +4 -2
  63. package/dist_ts/functions.ticketcli.js +70 -4
  64. package/dist_ts/functions.ticketlisting.d.ts +38 -0
  65. package/dist_ts/functions.ticketlisting.js +211 -0
  66. package/dist_ts/functions.ticketvalidation.d.ts +62 -0
  67. package/dist_ts/functions.ticketvalidation.js +41 -3
  68. package/dist_ts/functions.workercallervalidation.js +3 -2
  69. package/dist_ts/functions.workerprocessproof.d.ts +12 -0
  70. package/dist_ts/functions.workerprocessproof.js +32 -1
  71. package/dist_ts/interfaces.auth.d.ts +27 -3
  72. package/dist_ts/interfaces.auth.js +9 -1
  73. package/dist_ts/interfaces.lifecycle.d.ts +7 -1
  74. package/dist_ts/interfaces.push.d.ts +69 -0
  75. package/dist_ts/interfaces.push.js +25 -0
  76. package/dist_ts/plugins.d.ts +3 -1
  77. package/dist_ts/plugins.js +4 -2
  78. package/dist_ts_interfaces/devices.d.ts +178 -2
  79. package/dist_ts_interfaces/devices.js +24 -2
  80. package/dist_ts_interfaces/index.d.ts +1 -0
  81. package/dist_ts_interfaces/index.js +2 -1
  82. package/dist_ts_interfaces/mcprequests.d.ts +3 -2
  83. package/dist_ts_interfaces/mcprequests.js +3 -1
  84. package/dist_ts_interfaces/push.d.ts +166 -0
  85. package/dist_ts_interfaces/push.js +24 -0
  86. package/dist_ts_interfaces/requests.tickets.d.ts +31 -3
  87. package/dist_ts_interfaces/requests.tickets.js +2 -2
  88. package/dist_ts_interfaces/tickets.d.ts +174 -2
  89. package/dist_ts_interfaces/tickets.js +20 -2
  90. package/dist_ts_interfaces/workercallers.d.ts +43 -3
  91. package/package.json +2 -2
  92. package/readme.md +95 -14
  93. package/ts/00_commitinfo_data.ts +1 -1
  94. package/ts/aglapi/aglapisurface.document.ts +823 -5
  95. package/ts/aglapi/interfaces.ts +10 -0
  96. package/ts/classes.apnsclient.ts +389 -0
  97. package/ts/classes.authmodels.ts +21 -5
  98. package/ts/classes.authstore.ts +14 -1
  99. package/ts/classes.cli.ts +7 -0
  100. package/ts/classes.controller.ts +273 -7
  101. package/ts/classes.controllerdevices.ts +94 -12
  102. package/ts/classes.controllerpush.ts +351 -0
  103. package/ts/classes.fcmclient.ts +292 -0
  104. package/ts/classes.inbox.ts +13 -2
  105. package/ts/classes.mcpclient.ts +22 -7
  106. package/ts/classes.mcpcontrollerhost.ts +22 -1
  107. package/ts/classes.mcptools.ts +1 -0
  108. package/ts/classes.mcpvalidation.ts +2 -0
  109. package/ts/classes.mcpworkercaller.ts +24 -2
  110. package/ts/classes.pushdelivery.ts +378 -0
  111. package/ts/classes.pushhandover.ts +98 -0
  112. package/ts/classes.pushregistrations.ts +244 -0
  113. package/ts/classes.pushsettings.ts +428 -0
  114. package/ts/classes.ticketstore.ts +21 -3
  115. package/ts/classes.workercallers.ts +329 -37
  116. package/ts/driver/classes.directreports.ts +7 -1
  117. package/ts/fleet/classes.workerlaunches.ts +9 -7
  118. package/ts/fleet/classes.workers.ts +65 -2
  119. package/ts/functions.deviceapi.ts +54 -2
  120. package/ts/functions.mcptickettools.ts +3 -2
  121. package/ts/functions.pushcli.ts +212 -0
  122. package/ts/functions.pushcredentials.ts +129 -0
  123. package/ts/functions.pushwire.ts +106 -0
  124. package/ts/functions.remotecli.ts +3 -2
  125. package/ts/functions.ticketcli.ts +70 -5
  126. package/ts/functions.ticketlisting.ts +214 -0
  127. package/ts/functions.ticketvalidation.ts +41 -2
  128. package/ts/functions.workercallervalidation.ts +2 -1
  129. package/ts/functions.workerprocessproof.ts +34 -0
  130. package/ts/interfaces.auth.ts +26 -3
  131. package/ts/interfaces.lifecycle.ts +7 -1
  132. package/ts/interfaces.push.ts +78 -0
  133. package/ts/plugins.ts +3 -1
  134. package/ts_interfaces/devices.schema.json +327 -0
  135. package/ts_interfaces/devices.ts +206 -1
  136. package/ts_interfaces/index.ts +1 -0
  137. package/ts_interfaces/mcprequests.ts +3 -0
  138. package/ts_interfaces/push.ts +162 -0
  139. package/ts_interfaces/requests.tickets.ts +32 -2
  140. package/ts_interfaces/tickets.ts +136 -3
  141. package/ts_interfaces/workercallers.ts +34 -2
  142. package/ts_web/00_commitinfo_data.ts +1 -1
  143. package/ts_web/elements.inbox.ts +50 -9
@@ -111,6 +111,8 @@ export const aglApiMethods = {
111
111
  'agl.mcp.configuration.operation.recover': { use: 'excluded', exclusion: 'person', reason: ownerToken },
112
112
  'agl.mcp.configuration.operation.abandon': { use: 'excluded', exclusion: 'person', reason: ownerToken },
113
113
  'agl.mcp.ticket.list': { use: 'read', roles: tickets },
114
+ 'agl.mcp.ticket.page': { use: 'read', roles: tickets },
115
+ 'agl.mcp.ticket.overview': { use: 'read', roles: tickets },
114
116
  'agl.mcp.ticket.board': { use: 'read', roles: tickets },
115
117
  'agl.mcp.ticket.search': { use: 'read', roles: tickets },
116
118
  'agl.mcp.ticket.get': { use: 'read', roles: tickets },
@@ -155,6 +157,14 @@ export const aglApiMethods = {
155
157
  'agl.mcp.deploy.release': { use: 'excluded', exclusion: 'person', reason: ownerToken },
156
158
  'agl.mcp.deploy.ticket': { use: 'excluded', exclusion: 'person', reason: ownerToken },
157
159
  'agl.mcp.deploy.refresh': { use: 'excluded', exclusion: 'person', reason: ownerToken },
160
+ // The host's push credentials and previews (AGL-1639): only the owner sets them, with `agl push`.
161
+ 'agl.mcp.push.status': { use: 'excluded', exclusion: 'person', reason: ownerToken },
162
+ 'agl.mcp.push.apns.set': { use: 'excluded', exclusion: 'person', reason: ownerToken },
163
+ 'agl.mcp.push.apns.unset': { use: 'excluded', exclusion: 'person', reason: ownerToken },
164
+ 'agl.mcp.push.fcm.set': { use: 'excluded', exclusion: 'person', reason: ownerToken },
165
+ 'agl.mcp.push.fcm.unset': { use: 'excluded', exclusion: 'person', reason: ownerToken },
166
+ 'agl.mcp.push.previews': { use: 'excluded', exclusion: 'person', reason: ownerToken },
167
+ 'agl.mcp.push.test': { use: 'excluded', exclusion: 'person', reason: ownerToken },
158
168
  'agl.mcp.worker.enroll': { use: 'excluded', exclusion: 'transport',
159
169
  reason: 'It enrols the caller credential of a launched worker: the MCP channel itself.' },
160
170
  } as const satisfies Record<TControllerMcpMethod, TAglApiMethodUse>;
@@ -0,0 +1,389 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { TDevicePushData } from '../ts_interfaces/devices.js';
3
+ import type { IApnsCredential } from './classes.pushsettings.js';
4
+ import {
5
+ apnsHosts,
6
+ isPushVendorReason,
7
+ pushRequestTimeoutMs,
8
+ pushServiceEndpoints,
9
+ retryAfterMs,
10
+ type IPushEndpoints,
11
+ type IPushSender,
12
+ type IPushSendTarget,
13
+ type TApnsHost,
14
+ type TPushSendResult,
15
+ } from './interfaces.push.js';
16
+
17
+ /**
18
+ * Apple's push service, spoken directly (AGL-1639; Apple's "Sending notification requests to APNs", "Establishing a
19
+ * token-based connection to APNs" and "Handling notification responses from APNs"): HTTP/2 to api.push.apple.com or
20
+ * api.sandbox.push.apple.com by the device token's environment, `POST /3/device/<token>`, a provider token (an ES256
21
+ * JWT with the key id and the team id) in `authorization`, the bundle id as `apns-topic`.
22
+ */
23
+
24
+ /** Apple's limit for a notification's JSON payload (not VoIP). */
25
+ export const apnsPayloadMaximumBytes = 4096;
26
+ /** Apple's limit for `apns-collapse-id`. */
27
+ export const apnsCollapseIdMaximumBytes = 64;
28
+
29
+ /**
30
+ * Apple: a provider token is refreshed no more than once every 20 minutes and no less than once every 60 minutes, and a
31
+ * token older than an hour is refused (`ExpiredProviderToken`). This client signs a new one after 50 minutes.
32
+ */
33
+ export const apnsProviderTokenTimings = Object.freeze({ refreshMs: 50 * 60_000, minimumAgeMs: 20 * 60_000 });
34
+
35
+ /**
36
+ * A kept session without a request for `idleMs` is asked for a PING answer before the next request goes on it: a NAT or
37
+ * firewall may have dropped the connection without a word, and a request on it would wait the whole request timeout. A
38
+ * session that does not answer within `pingTimeoutMs` is destroyed and the request goes on a new one.
39
+ */
40
+ export const apnsLivenessTimings = Object.freeze({ idleMs: 60_000, pingTimeoutMs: 3_000 });
41
+
42
+ /** Apple: reuse a connection for hours; this client opens a new one after an hour without a request. */
43
+ const sessionIdleMs = 60 * 60_000;
44
+ /** An APNs answer is a small JSON object; anything past this is not read. */
45
+ const maximumAnswerBytes = 16 * 1024;
46
+
47
+ export interface IApnsRequest {
48
+ headers: Record<string, string>;
49
+ body: Buffer;
50
+ }
51
+
52
+ const badgeOf = (valueArg: string): number | undefined => (/^\d{1,9}$/u.test(valueArg) ? Number(valueArg) : undefined);
53
+
54
+ /**
55
+ * The APNs request for a notification: an alert push with `aps` (the alert, `thread-id` inbox or reports,
56
+ * `interruption-level` active or passive, the default sound except for a report's result, the badge where the payload
57
+ * carries one) for `inbox`, `summary`, `report` and `test`, a background push (`content-available`, priority 5) for `clear`, and the payload itself under `agl`. The
58
+ * payload's key is `apns-collapse-id`, so a notification sent again replaces the one shown. None when the payload breaks
59
+ * Apple's limits.
60
+ */
61
+ export const apnsRequest = (topicArg: string, payloadArg: TDevicePushData, expiresAtArg: number): IApnsRequest | undefined => {
62
+ const alert = (bodyArg: string, titleArg?: string) => (titleArg === undefined ? { body: bodyArg } : { title: titleArg, body: bodyArg });
63
+ let aps: Record<string, unknown>;
64
+ switch (payloadArg.type) {
65
+ case 'inbox': {
66
+ const badge = badgeOf(payloadArg.badge);
67
+ if (badge === undefined) return undefined;
68
+ aps = { alert: alert(payloadArg.body, payloadArg.title), badge, sound: 'default', 'thread-id': 'inbox', 'interruption-level': 'active' };
69
+ break;
70
+ }
71
+ case 'summary': {
72
+ const badge = badgeOf(payloadArg.badge);
73
+ if (badge === undefined) return undefined;
74
+ aps = { alert: alert(payloadArg.body), badge, sound: 'default', 'thread-id': 'inbox', 'interruption-level': 'active' };
75
+ break;
76
+ }
77
+ case 'report':
78
+ aps = { alert: alert(payloadArg.body, payloadArg.title), 'thread-id': 'reports', 'interruption-level': 'passive' };
79
+ break;
80
+ case 'test':
81
+ aps = { alert: alert(payloadArg.body), sound: 'default', 'thread-id': 'inbox', 'interruption-level': 'active' };
82
+ break;
83
+ case 'clear':
84
+ // A background push: the aps dictionary holds only content-available; the app sets its badge from the payload.
85
+ aps = { 'content-available': 1 };
86
+ break;
87
+ default:
88
+ return undefined;
89
+ }
90
+ const body = Buffer.from(JSON.stringify({ aps, agl: payloadArg }), 'utf8');
91
+ const collapseId = payloadArg.type === 'clear' ? undefined : payloadArg.key;
92
+ if (body.byteLength > apnsPayloadMaximumBytes
93
+ || (collapseId !== undefined && (collapseId.length === 0 || Buffer.byteLength(collapseId, 'utf8') > apnsCollapseIdMaximumBytes))) {
94
+ return undefined;
95
+ }
96
+ const background = payloadArg.type === 'clear';
97
+ return {
98
+ headers: {
99
+ 'apns-topic': topicArg,
100
+ 'apns-push-type': background ? 'background' : 'alert',
101
+ // Apple: a background push is always priority 5; an alert that waits for nobody (a report's result) too.
102
+ 'apns-priority': background || payloadArg.type === 'report' ? '5' : '10',
103
+ 'apns-expiration': String(Math.max(0, Math.floor(expiresAtArg / 1000))),
104
+ 'apns-id': plugins.crypto.randomUUID(),
105
+ ...(collapseId === undefined ? {} : { 'apns-collapse-id': collapseId }),
106
+ 'content-type': 'application/json',
107
+ },
108
+ body,
109
+ };
110
+ };
111
+
112
+ /** APNs reasons that refuse the host's credential (its key, team or topic): nothing is sent until the owner sets it again. */
113
+ const credentialReasons = new Set([
114
+ 'InvalidProviderToken', 'MissingProviderToken', 'BadEnvironmentKeyIdInToken', 'BadCertificate', 'BadCertificateEnvironment',
115
+ 'Forbidden', 'BadTopic', 'TopicDisallowed',
116
+ ]);
117
+ /** APNs reasons that end the connection's usefulness: the next send opens a new one. */
118
+ const connectionReasons = new Set(['UnrelatedKeyIdInToken', 'IdleTimeout', 'Shutdown']);
119
+
120
+ /**
121
+ * What an APNs answer means for the send (Apple's status and `reason` tables). `ExpiredProviderToken` is the host's
122
+ * clock or the token's age, never the credential: the client signs again once the token may be replaced.
123
+ */
124
+ export const apnsResult = (statusArg: number, reasonArg: string | undefined, retryAfterArg?: number): TPushSendResult => {
125
+ const vendorReason = isPushVendorReason(reasonArg) ? { vendorReason: reasonArg } : {};
126
+ const retry = retryAfterArg === undefined ? {} : { retryAfterMs: retryAfterArg };
127
+ if (statusArg === 200) return { outcome: 'delivered' };
128
+ if (statusArg === 410 || (statusArg === 400 && reasonArg === 'BadDeviceToken')) return { outcome: 'unregistered', ...vendorReason };
129
+ if (reasonArg !== undefined && (connectionReasons.has(reasonArg) || reasonArg === 'ExpiredProviderToken')) {
130
+ return { outcome: 'service_failed', ...vendorReason, ...retry };
131
+ }
132
+ if (statusArg === 403 || (reasonArg !== undefined && credentialReasons.has(reasonArg))) return { outcome: 'credential_refused', ...vendorReason };
133
+ if (statusArg === 429) return { outcome: 'rate_limited', ...vendorReason, ...retry };
134
+ if (statusArg === 400 || statusArg === 404 || statusArg === 405 || statusArg === 413) return { outcome: 'refused', ...vendorReason };
135
+ return { outcome: 'service_failed', ...vendorReason, ...retry };
136
+ };
137
+
138
+ interface ISessionEntry {
139
+ session: plugins.http2.ClientHttp2Session;
140
+ lastUsedAt: number;
141
+ /** The PING a request after `apnsLivenessTimings.idleMs` waits for; every request then waits for the same one. */
142
+ checking?: Promise<void>;
143
+ }
144
+
145
+ /**
146
+ * How a request ended: an answer, or no answer; `refusedStream` when the server refused the stream unprocessed (a GOAWAY
147
+ * reached the session first), which is safe to send again on a new session.
148
+ */
149
+ type TAnswer = { status: number; reason?: string; retryAfter?: number } | { failed: 'unreachable'; refusedStream?: true };
150
+
151
+ const expiredProviderToken = (answerArg: TAnswer): boolean => (
152
+ 'status' in answerArg && answerArg.status === 403 && answerArg.reason === 'ExpiredProviderToken'
153
+ );
154
+
155
+ export interface IApnsClientOptions {
156
+ credential: IApnsCredential;
157
+ /** Where the sessions connect; Apple's hosts when absent. For tests. */
158
+ endpoints?: IPushEndpoints;
159
+ now?: () => number;
160
+ }
161
+
162
+ /**
163
+ * One APNs credential's sender: an HTTP/2 session per host, opened on the first send and kept for the next ones, asked
164
+ * for a PING answer before a request after a minute without one, opened anew after a GOAWAY (a stream the server refused
165
+ * unprocessed is sent once more on the new one), an error, a timeout, an unanswered PING or an hour without a request,
166
+ * and destroyed by `close`; one provider token for every session, signed again after 50 minutes, or once at least 20
167
+ * minutes old when Apple calls it expired.
168
+ */
169
+ export class ApnsClient implements IPushSender {
170
+ private readonly sessions = new Map<TApnsHost, ISessionEntry>();
171
+ /** Sessions no longer used for new requests, until they close. */
172
+ private readonly retired = new Set<plugins.http2.ClientHttp2Session>();
173
+ private providerToken?: { value: string; issuedAt: number };
174
+ private closed = false;
175
+
176
+ constructor(private readonly options: IApnsClientOptions) {}
177
+
178
+ private now(): number {
179
+ return this.options.now?.() ?? Date.now();
180
+ }
181
+
182
+ public async send(targetArg: IPushSendTarget, payloadArg: TDevicePushData, expiresAtArg: number, signalArg: AbortSignal): Promise<TPushSendResult> {
183
+ if (this.closed || signalArg.aborted) return { outcome: 'unreachable' };
184
+ const request = apnsRequest(this.options.credential.topic, payloadArg, expiresAtArg);
185
+ // A token outside the device token's alphabet never reaches a request path.
186
+ if (!request || targetArg.environment === undefined || !/^[0-9a-f]{2,200}$/u.test(targetArg.token)) return { outcome: 'refused' };
187
+ const host = apnsHosts[targetArg.environment];
188
+ let token = this.currentProviderToken();
189
+ let answer = await this.post(host, targetArg.token, request, token.value, signalArg);
190
+ // The server's GOAWAY reached the session before the stream: nothing was processed, so it goes once more on a new one.
191
+ if ('failed' in answer && answer.refusedStream) answer = await this.post(host, targetArg.token, request, token.value, signalArg);
192
+ // Apple calls the token stale: a token old enough to be replaced (or one from the future, after the clock went back)
193
+ // is signed again once.
194
+ if (expiredProviderToken(answer) && !this.younger(token)) {
195
+ this.providerToken = undefined;
196
+ token = this.currentProviderToken();
197
+ answer = await this.post(host, targetArg.token, request, token.value, signalArg);
198
+ }
199
+ if ('failed' in answer) return { outcome: 'unreachable' };
200
+ if (expiredProviderToken(answer)) {
201
+ // A token younger than 20 minutes called stale: the host's clock is off, or was before a VM resumed. Not the
202
+ // credential: the send waits until the token may be signed again, so Apple's 20-minute rule holds, and heals
203
+ // once the clock is right.
204
+ return {
205
+ outcome: 'service_failed', vendorReason: 'ExpiredProviderToken',
206
+ retryAfterMs: Math.max(0, apnsProviderTokenTimings.minimumAgeMs - (this.now() - token.issuedAt)),
207
+ };
208
+ }
209
+ return apnsResult(answer.status, answer.reason, answer.retryAfter);
210
+ }
211
+
212
+ /** Whether the token is younger than Apple lets a token be replaced; a token from the future is not. */
213
+ private younger(tokenArg: { issuedAt: number }): boolean {
214
+ const age = this.now() - tokenArg.issuedAt;
215
+ return age >= 0 && age < apnsProviderTokenTimings.minimumAgeMs;
216
+ }
217
+
218
+ /**
219
+ * Destroys every session; a request still running ends as unreachable. A session a GOAWAY closed gracefully ends its
220
+ * connection once the server closes it, as Apple does after a GOAWAY.
221
+ */
222
+ public async close(): Promise<void> {
223
+ this.closed = true;
224
+ const sessions = [...[...this.sessions.values()].map((entryArg) => entryArg.session), ...this.retired];
225
+ this.sessions.clear();
226
+ this.retired.clear();
227
+ for (const session of sessions) if (!session.destroyed) session.destroy();
228
+ }
229
+
230
+ /** Whether the client holds no session: every one it opened is destroyed or closing. */
231
+ public idle(): boolean {
232
+ return this.sessions.size === 0 && this.retired.size === 0;
233
+ }
234
+
235
+ /** The provider token: the held one while younger than 50 minutes, else a new one. */
236
+ private currentProviderToken(): { value: string; issuedAt: number } {
237
+ const now = this.now();
238
+ if (this.providerToken && now - this.providerToken.issuedAt < apnsProviderTokenTimings.refreshMs) return this.providerToken;
239
+ const { keyId, teamId, key } = this.options.credential;
240
+ const encode = (valueArg: object) => Buffer.from(JSON.stringify(valueArg), 'utf8').toString('base64url');
241
+ const input = `${encode({ alg: 'ES256', kid: keyId })}.${encode({ iss: teamId, iat: Math.floor(now / 1000) })}`;
242
+ const signature = plugins.crypto.sign('sha256', Buffer.from(input, 'utf8'), { key, dsaEncoding: 'ieee-p1363' });
243
+ this.providerToken = { value: `${input}.${signature.toString('base64url')}`, issuedAt: now };
244
+ return this.providerToken;
245
+ }
246
+
247
+ /**
248
+ * The open session to `hostArg`, or a new one. A session without a request for a minute answers a PING first, or is
249
+ * destroyed and replaced.
250
+ */
251
+ private async session(hostArg: TApnsHost): Promise<ISessionEntry> {
252
+ for (;;) {
253
+ const held = this.sessions.get(hostArg);
254
+ if (!held || held.session.closed || held.session.destroyed || this.now() - held.lastUsedAt >= sessionIdleMs) break;
255
+ if (held.checking === undefined && this.now() - held.lastUsedAt < apnsLivenessTimings.idleMs) {
256
+ held.lastUsedAt = this.now();
257
+ return held;
258
+ }
259
+ held.checking ??= this.ping(hostArg, held).finally(() => { held.checking = undefined; held.lastUsedAt = this.now(); });
260
+ await held.checking;
261
+ if (this.closed) throw new Error('The APNs client is closed.');
262
+ }
263
+ return this.open(hostArg);
264
+ }
265
+
266
+ /** Waits for the session's PING answer; a session that gives none in time, or fails, is destroyed. */
267
+ private ping(hostArg: TApnsHost, entryArg: ISessionEntry): Promise<void> {
268
+ return new Promise<void>((resolve) => {
269
+ const timer = setTimeout(() => { this.retire(hostArg, entryArg, 'destroy'); resolve(); }, apnsLivenessTimings.pingTimeoutMs);
270
+ const answered = (errorArg: Error | null): void => {
271
+ clearTimeout(timer);
272
+ if (errorArg) this.retire(hostArg, entryArg, 'destroy');
273
+ resolve();
274
+ };
275
+ try {
276
+ if (!entryArg.session.ping(answered)) answered(new Error('The PING was not sent.'));
277
+ } catch (errorArg) {
278
+ answered(errorArg as Error);
279
+ }
280
+ });
281
+ }
282
+
283
+ /** A new session to `hostArg`, replacing the held one: after an hour without a request it may be gone without a word. */
284
+ private open(hostArg: TApnsHost): ISessionEntry {
285
+ const now = this.now();
286
+ const held = this.sessions.get(hostArg);
287
+ if (held) this.retire(hostArg, held, 'destroy');
288
+ const session = plugins.http2.connect((this.options.endpoints ?? pushServiceEndpoints).apns(hostArg));
289
+ const entry: ISessionEntry = { session, lastUsedAt: now };
290
+ // A GOAWAY ends the session for new requests (Node closes it once its streams end); an error ends it at once.
291
+ session.on('goaway', () => this.retire(hostArg, entry, 'close'));
292
+ session.on('error', () => this.retire(hostArg, entry, 'destroy'));
293
+ session.on('close', () => {
294
+ this.retired.delete(session);
295
+ if (this.sessions.get(hostArg) === entry) this.sessions.delete(hostArg);
296
+ });
297
+ this.sessions.set(hostArg, entry);
298
+ return entry;
299
+ }
300
+
301
+ /**
302
+ * Takes a session out of use: `close` lets its streams end (a GOAWAY, or a reason Apple gives for the connection),
303
+ * `destroy` ends it at once (an error, a stream that failed or timed out, an hour idle).
304
+ */
305
+ private retire(hostArg: TApnsHost, entryArg: ISessionEntry, howArg: 'close' | 'destroy'): void {
306
+ if (this.sessions.get(hostArg) === entryArg) this.sessions.delete(hostArg);
307
+ if (entryArg.session.destroyed) return;
308
+ if (howArg === 'destroy') {
309
+ this.retired.delete(entryArg.session);
310
+ entryArg.session.destroy();
311
+ return;
312
+ }
313
+ this.retired.add(entryArg.session);
314
+ if (!entryArg.session.closed) entryArg.session.close();
315
+ }
316
+
317
+ private async post(hostArg: TApnsHost, deviceTokenArg: string, requestArg: IApnsRequest, providerTokenArg: string, signalArg: AbortSignal): Promise<TAnswer> {
318
+ if (this.closed || signalArg.aborted) return { failed: 'unreachable' };
319
+ let entry: ISessionEntry;
320
+ try {
321
+ entry = await this.session(hostArg);
322
+ } catch {
323
+ return { failed: 'unreachable' };
324
+ }
325
+ if (this.closed || signalArg.aborted) return { failed: 'unreachable' };
326
+ let stream: plugins.http2.ClientHttp2Stream;
327
+ try {
328
+ stream = entry.session.request({
329
+ ':method': 'POST',
330
+ ':authority': hostArg,
331
+ ':path': `/3/device/${deviceTokenArg}`,
332
+ authorization: `bearer ${providerTokenArg}`,
333
+ ...requestArg.headers,
334
+ });
335
+ } catch {
336
+ this.retire(hostArg, entry, 'destroy');
337
+ return { failed: 'unreachable' };
338
+ }
339
+ return await new Promise<TAnswer>((resolve) => {
340
+ let settled = false;
341
+ let status = 0;
342
+ let retryAfter: number | undefined;
343
+ const chunks: Buffer[] = [];
344
+ let size = 0;
345
+ const finish = (answerArg: TAnswer): void => {
346
+ if (settled) return;
347
+ settled = true;
348
+ clearTimeout(timer);
349
+ signalArg.removeEventListener('abort', abort);
350
+ if ('failed' in answerArg && !answerArg.refusedStream) {
351
+ if (!stream.closed && !stream.destroyed) stream.close(plugins.http2.constants.NGHTTP2_CANCEL);
352
+ // A session that timed out or failed a stream may be dead: the next send opens a new one.
353
+ this.retire(hostArg, entry, 'destroy');
354
+ }
355
+ resolve(answerArg);
356
+ };
357
+ const abort = (): void => finish({ failed: 'unreachable' });
358
+ const timer = setTimeout(abort, pushRequestTimeoutMs);
359
+ signalArg.addEventListener('abort', abort, { once: true });
360
+ stream.on('response', (headersArg) => {
361
+ status = Number(headersArg[':status']);
362
+ retryAfter = retryAfterMs(headersArg['retry-after'], this.now());
363
+ });
364
+ stream.on('data', (chunkArg: Buffer) => {
365
+ size += chunkArg.byteLength;
366
+ if (size <= maximumAnswerBytes) chunks.push(chunkArg);
367
+ });
368
+ // The close that follows says why the stream ended.
369
+ stream.on('error', () => undefined);
370
+ stream.on('close', () => {
371
+ if (!status) {
372
+ finish(stream.rstCode === plugins.http2.constants.NGHTTP2_REFUSED_STREAM
373
+ ? { failed: 'unreachable', refusedStream: true } : { failed: 'unreachable' });
374
+ return;
375
+ }
376
+ let reason: string | undefined;
377
+ if (status !== 200 && size <= maximumAnswerBytes) {
378
+ try {
379
+ const answer = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { reason?: unknown };
380
+ reason = isPushVendorReason(answer?.reason) ? answer.reason : undefined;
381
+ } catch { /* An answer without a readable reason is judged by its status. */ }
382
+ }
383
+ if (reason !== undefined && connectionReasons.has(reason)) this.retire(hostArg, entry, 'close');
384
+ finish({ status, ...(reason === undefined ? {} : { reason }), ...(retryAfter === undefined ? {} : { retryAfter }) });
385
+ });
386
+ stream.end(requestArg.body);
387
+ });
388
+ }
389
+ }
@@ -5,6 +5,7 @@ import { isControllerTerminalAgentSessionId } from './functions.terminalagents.j
5
5
  import { resourceKindAcceptsTerminalSubject } from './functions.resourceattachments.js';
6
6
  import { isAgentMessageSubject } from './functions.agentmessage.js';
7
7
  import { canonicalGatewaySources } from './functions.controlleradmission.js';
8
+ import { isAppleId, isBundleId, isFirebaseProjectId, isServiceAccountEmail } from './functions.pushcredentials.js';
8
9
  import {
9
10
  controllerAuditEventTypes,
10
11
  type IControllerAuditEvent,
@@ -413,15 +414,30 @@ const isAuditGateway = (typeArg: string, valueArg: unknown): valueArg is IContro
413
414
  && isAuditGatewayText(valueArg.routeKey, 1024)
414
415
  && (valueArg.rotate === undefined || typeof valueArg.rotate === 'boolean');
415
416
 
417
+ /** What a `push.*` event records of its change: the identifiers it set, never a key (AGL-1639). */
418
+ const isAuditPush = (typeArg: string, valueArg: unknown): boolean => isPlainObject(valueArg) && (
419
+ typeArg === 'push.apns.set'
420
+ ? hasExactKeys(valueArg, ['keyId', 'teamId', 'topic']) && isAppleId(valueArg.keyId) && isAppleId(valueArg.teamId) && isBundleId(valueArg.topic)
421
+ : typeArg === 'push.fcm.set'
422
+ ? hasExactKeys(valueArg, ['projectId', 'clientEmail']) && isFirebaseProjectId(valueArg.projectId) && isServiceAccountEmail(valueArg.clientEmail)
423
+ : typeArg === 'push.previews'
424
+ ? hasExactKeys(valueArg, ['previews']) && typeof valueArg.previews === 'boolean'
425
+ : typeArg === 'push.test' && hasExactKeys(valueArg, ['devices', 'delivered'])
426
+ && Number.isSafeInteger(valueArg.devices) && Number.isSafeInteger(valueArg.delivered)
427
+ && (valueArg.delivered as number) >= 0 && (valueArg.devices as number) >= (valueArg.delivered as number)
428
+ );
429
+
416
430
  /**
417
431
  * `details` on a type this release knows: only `remote.set` and `remote.unset` record a `remoteMove`, and only a move
418
- * from one canonical origin and RP ID to another; only `remote.gateway.*` records a `gateway`.
432
+ * from one canonical origin and RP ID to another; only `remote.gateway.*` records a `gateway`; only `push.apns.set`,
433
+ * `push.fcm.set`, `push.previews` and `push.test` record a `push`.
419
434
  */
420
435
  const hasKnownAuditDetails = (typeArg: string, detailsArg: Record<string, unknown>): boolean =>
421
436
  (!Object.hasOwn(detailsArg, 'remoteMove')
422
437
  || ((typeArg === 'remote.set' || typeArg === 'remote.unset') && isAuditRemoteMove(detailsArg.remoteMove)))
423
438
  && (!Object.hasOwn(detailsArg, 'gateway')
424
- || (typeArg.startsWith('remote.gateway.') && isAuditGateway(typeArg, detailsArg.gateway)));
439
+ || (typeArg.startsWith('remote.gateway.') && isAuditGateway(typeArg, detailsArg.gateway)))
440
+ && (!Object.hasOwn(detailsArg, 'push') || isAuditPush(typeArg, detailsArg.push));
425
441
 
426
442
  /**
427
443
  * A stored audit event. The log is shared with later releases, so a type this release does not know (a later
@@ -468,9 +484,9 @@ export const assertControllerAuditEventDocument = (
468
484
  throw new Error('Invalid controller audit event.');
469
485
  }
470
486
  if (Object.hasOwn(valueArg, 'localCli')) {
471
- // Local configuration and the offline `agl remote` commands are the actions a local OS user takes; a type this
472
- // release does not know leaves that rule to the release that knows it.
473
- if (known && !type.startsWith('configuration.') && !type.startsWith('remote.')) {
487
+ // Local configuration, the offline `agl remote` commands and `agl push` are the actions a local OS user takes; a
488
+ // type this release does not know leaves that rule to the release that knows it.
489
+ if (known && !type.startsWith('configuration.') && !type.startsWith('remote.') && !type.startsWith('push.')) {
474
490
  throw new Error('Invalid local configuration audit event.');
475
491
  }
476
492
  assertConfigurationLocalCliActor(valueArg.localCli);
@@ -11,6 +11,9 @@ import { ControllerCodexOriginMigrationModel } from '../ts_migration/v29_codexor
11
11
  import { ControllerCodexConnectionStore } from './classes.codexconnectionstore.js';
12
12
  import { ControllerTrustedProxySecretModel } from './classes.trustedproxysecrets.js';
13
13
  import { ControllerDeviceModel, deleteControllerDevices } from './classes.controllerdevices.js';
14
+ import { ControllerPushRegistrationModel } from './classes.pushregistrations.js';
15
+ import { ControllerPushSettingsModel } from './classes.pushsettings.js';
16
+ import { ControllerPushHandoverModel } from './classes.pushhandover.js';
14
17
  import { ControllerGatewayClientModel } from './classes.gatewayclientstore.js';
15
18
  import { ControllerClaudeSessionStore } from './classes.claudesessionstore.js';
16
19
  import { ControllerClaudeSessionModel } from './classes.claudesessionmodels.js';
@@ -809,6 +812,9 @@ const setAuthStoreModelManager = (
809
812
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerTrackedConversationModel);
810
813
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerTrustedProxySecretModel);
811
814
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerDeviceModel);
815
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerPushRegistrationModel);
816
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerPushSettingsModel);
817
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerPushHandoverModel);
812
818
  plugins.nosqldb.setDefaultManagerForDoc(managerArg, ControllerGatewayClientModel);
813
819
  plugins.nosqldb.setDefaultManagerForDoc(
814
820
  managerArg,
@@ -1102,10 +1108,15 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1102
1108
  await ControllerTrackedConversationModel.init();
1103
1109
  await ControllerTrustedProxySecretModel.init();
1104
1110
  await ControllerDeviceModel.init();
1111
+ await ControllerPushRegistrationModel.init();
1112
+ await ControllerPushSettingsModel.init();
1113
+ await ControllerPushHandoverModel.init();
1105
1114
  await ControllerGatewayClientModel.init();
1106
- // `moveRuntimeConfig` changes the configuration and deletes the paired devices in one transaction.
1115
+ // `moveRuntimeConfig` changes the configuration and deletes the paired devices and their push registrations in
1116
+ // one transaction; a revocation deletes a device and its registration in one.
1107
1117
  await ControllerAuthModel.exact.prepare();
1108
1118
  await ControllerDeviceModel.exact.prepare();
1119
+ await ControllerPushRegistrationModel.exact.prepare();
1109
1120
  await new PostDatabaseDocumentMigrationRunner(this.database).run();
1110
1121
  this.initialized = true;
1111
1122
  if (!this.closeStarted) this.projectMutationAdmissionOpen = true;
@@ -1959,6 +1970,8 @@ export class SmartDataAuthStore implements IAuthStore, IAuthStoreSessionIdentity
1959
1970
  rpId: eventArg.details.remoteMove.target.rpId,
1960
1971
  },
1961
1972
  },
1973
+ } : 'push' in eventArg.details ? {
1974
+ push: { ...eventArg.details.push },
1962
1975
  } : {
1963
1976
  gateway: {
1964
1977
  gatewayUrl: eventArg.details.gateway.gatewayUrl,
package/ts/classes.cli.ts CHANGED
@@ -148,6 +148,7 @@ Usage:
148
148
  ${currentCliName} feed list [--state failed] [--json] | acknowledge <row-id> --updated-at <ms> [--json]
149
149
  ${currentCliName} deploy status [TARGET] | history TARGET | probe TARGET [--json]
150
150
  ${currentCliName} release status [REPO] [--json]
151
+ ${currentCliName} push status [--json] | apns set|unset | fcm set|unset | previews on|off | test [--port 4097] [options]
151
152
 
152
153
  Commands:
153
154
  start Start ${currentRuntimeName} as a detached process (Linux and macOS)
@@ -160,6 +161,7 @@ Commands:
160
161
  feed List the sidebar's session feed and acknowledge failed rows as the owner (feed --help)
161
162
  deploy What each deploy target runs, as its probe observed it, its history, and a probe now (deploy --help)
162
163
  release A repository's newest release tag, its release plans and what the next release ships (release --help)
164
+ push Notifications to paired devices: the host's APNs and FCM credentials and previews (push --help)
163
165
  stop Verify and stop the live ${currentRuntimeName} process
164
166
  restart Stop the live ${currentRuntimeName} process and start it again (sessions are not continued)
165
167
  service Run ${currentRuntimeName} as the systemd user unit ${controllerServiceUnitName} (Linux, pnpm-global install)
@@ -2050,6 +2052,11 @@ const runCliCommand = async (testArgvArg?: string[]): Promise<void> => {
2050
2052
  await runDeployCli(runtimeArguments[0], runtimeArguments.slice(1));
2051
2053
  return;
2052
2054
  }
2055
+ if (runtimeArguments[0] === 'push') {
2056
+ const { runPushCli } = await import('./functions.pushcli.js');
2057
+ await runPushCli(runtimeArguments.slice(1));
2058
+ return;
2059
+ }
2053
2060
  if (runtimeArguments[0] === 'feed') {
2054
2061
  const { runFeedCli } = await import('./functions.feedcli.js');
2055
2062
  await runFeedCli(runtimeArguments.slice(1));