agl 43.7.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.
- package/changelog.md +17 -0
- package/dist_serve/bundle.js +786 -786
- package/dist_serve/bundle.js.map +2 -2
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/aglapi/interfaces.d.ts +35 -0
- package/dist_ts/aglapi/interfaces.js +9 -1
- package/dist_ts/classes.apnsclient.d.ts +97 -0
- package/dist_ts/classes.apnsclient.js +363 -0
- package/dist_ts/classes.authmodels.js +19 -6
- package/dist_ts/classes.authstore.js +15 -2
- package/dist_ts/classes.cli.js +8 -1
- package/dist_ts/classes.controller.d.ts +30 -3
- package/dist_ts/classes.controller.js +250 -9
- package/dist_ts/classes.controllerdevices.d.ts +35 -7
- package/dist_ts/classes.controllerdevices.js +86 -13
- package/dist_ts/classes.controllerpush.d.ts +111 -0
- package/dist_ts/classes.controllerpush.js +299 -0
- package/dist_ts/classes.fcmclient.d.ts +78 -0
- package/dist_ts/classes.fcmclient.js +278 -0
- package/dist_ts/classes.inbox.d.ts +10 -2
- package/dist_ts/classes.inbox.js +9 -2
- package/dist_ts/classes.mcpclient.d.ts +5 -0
- package/dist_ts/classes.mcpclient.js +18 -6
- package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -0
- package/dist_ts/classes.mcpcontrollerhost.js +19 -1
- package/dist_ts/classes.mcpvalidation.js +4 -1
- package/dist_ts/classes.mcpworkercaller.d.ts +6 -0
- package/dist_ts/classes.mcpworkercaller.js +26 -4
- package/dist_ts/classes.pushdelivery.d.ts +115 -0
- package/dist_ts/classes.pushdelivery.js +311 -0
- package/dist_ts/classes.pushhandover.d.ts +46 -0
- package/dist_ts/classes.pushhandover.js +131 -0
- package/dist_ts/classes.pushregistrations.d.ts +96 -0
- package/dist_ts/classes.pushregistrations.js +263 -0
- package/dist_ts/classes.pushsettings.d.ts +125 -0
- package/dist_ts/classes.pushsettings.js +377 -0
- package/dist_ts/classes.workercallers.d.ts +73 -2
- package/dist_ts/classes.workercallers.js +354 -43
- package/dist_ts/driver/classes.directreports.d.ts +5 -0
- package/dist_ts/driver/classes.directreports.js +3 -2
- package/dist_ts/fleet/classes.workerlaunches.d.ts +6 -4
- package/dist_ts/fleet/classes.workerlaunches.js +10 -9
- package/dist_ts/fleet/classes.workers.d.ts +12 -2
- package/dist_ts/fleet/classes.workers.js +82 -2
- package/dist_ts/functions.deviceapi.d.ts +23 -3
- package/dist_ts/functions.deviceapi.js +41 -3
- package/dist_ts/functions.pushcli.d.ts +43 -0
- package/dist_ts/functions.pushcli.js +201 -0
- package/dist_ts/functions.pushcredentials.d.ts +53 -0
- package/dist_ts/functions.pushcredentials.js +111 -0
- package/dist_ts/functions.pushwire.d.ts +8 -0
- package/dist_ts/functions.pushwire.js +83 -0
- package/dist_ts/functions.remotecli.d.ts +2 -2
- package/dist_ts/functions.remotecli.js +4 -4
- package/dist_ts/functions.workercallervalidation.js +3 -2
- package/dist_ts/functions.workerprocessproof.d.ts +12 -0
- package/dist_ts/functions.workerprocessproof.js +32 -1
- package/dist_ts/interfaces.auth.d.ts +27 -3
- package/dist_ts/interfaces.auth.js +9 -1
- package/dist_ts/interfaces.lifecycle.d.ts +7 -1
- package/dist_ts/interfaces.push.d.ts +69 -0
- package/dist_ts/interfaces.push.js +25 -0
- package/dist_ts/plugins.d.ts +3 -1
- package/dist_ts/plugins.js +4 -2
- package/dist_ts_interfaces/devices.d.ts +178 -2
- package/dist_ts_interfaces/devices.js +24 -2
- package/dist_ts_interfaces/index.d.ts +1 -0
- package/dist_ts_interfaces/index.js +2 -1
- package/dist_ts_interfaces/mcprequests.d.ts +3 -2
- package/dist_ts_interfaces/mcprequests.js +3 -1
- package/dist_ts_interfaces/push.d.ts +166 -0
- package/dist_ts_interfaces/push.js +24 -0
- package/dist_ts_interfaces/workercallers.d.ts +43 -3
- package/package.json +1 -1
- package/readme.md +64 -11
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/aglapi/interfaces.ts +8 -0
- package/ts/classes.apnsclient.ts +389 -0
- package/ts/classes.authmodels.ts +21 -5
- package/ts/classes.authstore.ts +14 -1
- package/ts/classes.cli.ts +7 -0
- package/ts/classes.controller.ts +273 -7
- package/ts/classes.controllerdevices.ts +94 -12
- package/ts/classes.controllerpush.ts +351 -0
- package/ts/classes.fcmclient.ts +292 -0
- package/ts/classes.inbox.ts +13 -2
- package/ts/classes.mcpclient.ts +20 -5
- package/ts/classes.mcpcontrollerhost.ts +20 -0
- package/ts/classes.mcpvalidation.ts +2 -0
- package/ts/classes.mcpworkercaller.ts +24 -2
- package/ts/classes.pushdelivery.ts +378 -0
- package/ts/classes.pushhandover.ts +98 -0
- package/ts/classes.pushregistrations.ts +244 -0
- package/ts/classes.pushsettings.ts +428 -0
- package/ts/classes.workercallers.ts +329 -37
- package/ts/driver/classes.directreports.ts +7 -1
- package/ts/fleet/classes.workerlaunches.ts +9 -7
- package/ts/fleet/classes.workers.ts +65 -2
- package/ts/functions.deviceapi.ts +52 -2
- package/ts/functions.pushcli.ts +212 -0
- package/ts/functions.pushcredentials.ts +129 -0
- package/ts/functions.pushwire.ts +106 -0
- package/ts/functions.remotecli.ts +3 -2
- package/ts/functions.workercallervalidation.ts +2 -1
- package/ts/functions.workerprocessproof.ts +34 -0
- package/ts/interfaces.auth.ts +26 -3
- package/ts/interfaces.lifecycle.ts +7 -1
- package/ts/interfaces.push.ts +78 -0
- package/ts/plugins.ts +3 -1
- package/ts_interfaces/devices.schema.json +327 -0
- package/ts_interfaces/devices.ts +206 -1
- package/ts_interfaces/index.ts +1 -0
- package/ts_interfaces/mcprequests.ts +3 -0
- package/ts_interfaces/push.ts +162 -0
- package/ts_interfaces/workercallers.ts +34 -2
- package/ts_web/00_commitinfo_data.ts +1 -1
|
@@ -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
|
+
}
|
package/ts/classes.inbox.ts
CHANGED
|
@@ -24,7 +24,10 @@ export interface IInboxSources {
|
|
|
24
24
|
* the part of them a failed partial read could not renew. A read that fails keeps the source's previous items.
|
|
25
25
|
*/
|
|
26
26
|
read(sourceArg: TInboxSource, previousArg: readonly TControllerInboxItem[], signalArg: AbortSignal): Promise<TControllerInboxItem[]>;
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Whether a browser or a device receives controller events, or a notification could go out (a registered device on
|
|
29
|
+
* a platform the host can send on); without either the Inbox only marks its sources stale.
|
|
30
|
+
*/
|
|
28
31
|
hasViewers(): Promise<boolean>;
|
|
29
32
|
publish(deltaArg: TControllerInboxDelta): void;
|
|
30
33
|
reportError(messageArg: string, errorArg: unknown): void;
|
|
@@ -72,7 +75,7 @@ export const boundInboxItem = (itemArg: TControllerInboxItem): TControllerInboxI
|
|
|
72
75
|
* deltas. Nothing is stored: every item is read from the component that owns it, so an answer anywhere removes it.
|
|
73
76
|
*
|
|
74
77
|
* Events mark the sources they concern stale; a pass reads only the stale ones, coalesced, and only while a browser
|
|
75
|
-
* or a device is connected. `list()` reads every stale source first.
|
|
78
|
+
* or a device is connected or a notification could go out. `list()` reads every stale source first.
|
|
76
79
|
*/
|
|
77
80
|
export class ControllerInbox {
|
|
78
81
|
private readonly abort = new AbortController();
|
|
@@ -99,6 +102,14 @@ export class ControllerInbox {
|
|
|
99
102
|
public async list(): Promise<IControllerInboxSnapshot> {
|
|
100
103
|
this.abort.signal.throwIfAborted();
|
|
101
104
|
await this.enqueuePass();
|
|
105
|
+
return this.current();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* What the last pass published, reading nothing: for a consumer of the published deltas that met a `reset` (the push
|
|
110
|
+
* trigger), never a second computation of the Inbox.
|
|
111
|
+
*/
|
|
112
|
+
public current(): IControllerInboxSnapshot {
|
|
102
113
|
return { epoch: this.published.epoch, revision: this.published.revision, items: this.published.values(), total: this.total, limited: this.limited };
|
|
103
114
|
}
|
|
104
115
|
|
package/ts/classes.mcpclient.ts
CHANGED
|
@@ -10,8 +10,10 @@ import { readTicketRevisionConflict, ticketErrorMessages, type TTicketClientErro
|
|
|
10
10
|
import { assertMcpTicketRequest, assertTicketResponse } from './functions.ticketvalidation.js';
|
|
11
11
|
import { assertSessionFeedWireRequest, assertSessionFeedWireResponse } from './functions.sessionfeedvalidation.js';
|
|
12
12
|
import { assertFleetDeployResponse, assertFleetDeployWireRequest } from './fleet/functions.deployvalidation.js';
|
|
13
|
+
import { assertPushResponse, assertPushWireRequest, isControllerMcpPushMethod, redactPushRequest } from './functions.pushwire.js';
|
|
13
14
|
import { fleetDeployRefreshClientMarginMs, fleetDeployRefreshWaitMs, type IFleetDeployOperations, type TFleetDeployOperation } from '../ts_interfaces/deployments.js';
|
|
14
15
|
import type { IReq_ControllerMcpSessionFeedAcknowledge, IReq_ControllerMcpSessionFeedList } from '../ts_interfaces/sessionfeed.js';
|
|
16
|
+
import type { IPushOperations, TControllerMcpPushMethod, TPushOperation } from '../ts_interfaces/push.js';
|
|
15
17
|
import { isProxyCapacityAnswer, type IProxyCapacityAnswer, type IProxyCapacityRequest } from '../ts_interfaces/proxycapacity.js';
|
|
16
18
|
import {
|
|
17
19
|
controllerMcpNativeDeliveries,
|
|
@@ -358,6 +360,10 @@ const assertResponsePayload = (
|
|
|
358
360
|
assertFleetDeployResponse(methodArg, valueArg);
|
|
359
361
|
return;
|
|
360
362
|
}
|
|
363
|
+
if (isControllerMcpPushMethod(methodArg)) {
|
|
364
|
+
assertPushResponse(methodArg, valueArg);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
361
367
|
if (methodArg.startsWith('agl.mcp.ticket.')) {
|
|
362
368
|
assertTicketResponse(methodArg, valueArg);
|
|
363
369
|
return;
|
|
@@ -790,6 +796,14 @@ export class ControllerMcpClient {
|
|
|
790
796
|
operation === 'refresh' ? Math.max(this.requestTimeoutMs, deployRefreshRequestTimeoutMs) : undefined,
|
|
791
797
|
) as Promise<IFleetDeployOperations[TOperation]['response']>;
|
|
792
798
|
}
|
|
799
|
+
/** The host's push settings as the local owner reads and changes them (`agl push`, AGL-1639). */
|
|
800
|
+
public async push<TOperation extends TPushOperation>(operation: TOperation,
|
|
801
|
+
request: IPushOperations[TOperation]['request'] & { ownerToken: string }, signal?: AbortSignal,
|
|
802
|
+
): Promise<IPushOperations[TOperation]['response']> {
|
|
803
|
+
const method = `agl.mcp.push.${operation}` as const;
|
|
804
|
+
const wireRequest = assertPushWireRequest(method, request);
|
|
805
|
+
return this.dispatchAfterHandshake(method as TControllerMcpPushMethod, wireRequest as never, signal, operation !== 'status') as Promise<IPushOperations[TOperation]['response']>;
|
|
806
|
+
}
|
|
793
807
|
public async fleetStatus(id: string, ownerToken: string, signal?: AbortSignal, ticketKey?: string): Promise<IFleetOperation> {
|
|
794
808
|
return this.dispatchAfterHandshake('agl.mcp.fleet.status', { id, ownerToken, ...(ticketKey ? { ticketKey } : {}) }, signal, false);
|
|
795
809
|
}
|
|
@@ -972,11 +986,12 @@ export class ControllerMcpClient {
|
|
|
972
986
|
|| decoded.method !== methodArg
|
|
973
987
|
|| !plugins.util.isDeepStrictEqual(
|
|
974
988
|
decoded.request,
|
|
975
|
-
(methodArg
|
|
976
|
-
|| methodArg.startsWith('agl.mcp.
|
|
977
|
-
|
|
978
|
-
...(
|
|
979
|
-
|
|
989
|
+
isControllerMcpPushMethod(methodArg) ? redactPushRequest(requestArg as Record<string, unknown>)
|
|
990
|
+
: (methodArg.startsWith('agl.mcp.configuration.') || methodArg.startsWith('agl.mcp.ticket.') || methodArg.startsWith('agl.mcp.fleet.')
|
|
991
|
+
|| methodArg.startsWith('agl.mcp.deploy.'))
|
|
992
|
+
? { ...requestArg, ...(Object.hasOwn(requestArg, 'ownerToken') ? { ownerToken: '[redacted]' } : {}),
|
|
993
|
+
...(methodArg === 'agl.mcp.configuration.master.save' ? { masterJson: '[redacted]' } : {}) }
|
|
994
|
+
: requestArg,
|
|
980
995
|
)
|
|
981
996
|
|| !controllerMcpValueIsRecord(decoded.response)
|
|
982
997
|
|| !controllerMcpValueIsRecord(decoded.correlation)
|
|
@@ -31,6 +31,8 @@ import type { IFleetOperation } from '../ts_interfaces/fleet.js';
|
|
|
31
31
|
import { controllerMcpTicketMethods, type TControllerMcpTicketTypedRequest } from '../ts_interfaces/requests.tickets.js';
|
|
32
32
|
import type { IReq_ControllerMcpSessionFeedAcknowledge, IReq_ControllerMcpSessionFeedList } from '../ts_interfaces/sessionfeed.js';
|
|
33
33
|
import { controllerMcpDeployMethods, type TControllerMcpDeployMethod, type TControllerMcpDeployTypedRequest } from '../ts_interfaces/deployments.js';
|
|
34
|
+
import { controllerMcpPushMethods, pushErrorCodes, type TControllerMcpPushMethod, type TControllerMcpPushTypedRequest } from '../ts_interfaces/push.js';
|
|
35
|
+
import { redactPushRequest } from './functions.pushwire.js';
|
|
34
36
|
import { deployErrorCodes } from './fleet/classes.deploymonitor.js';
|
|
35
37
|
import { readTicketRevisionConflict, ticketErrorMessages, type TTicketOperation, type TTicketRequest, type TTicketResponse } from '../ts_interfaces/tickets.js';
|
|
36
38
|
import { ticketOperation } from './functions.ticketvalidation.js';
|
|
@@ -94,6 +96,8 @@ export interface IControllerMcpPrivateApi {
|
|
|
94
96
|
fleet?: (method: string, request: Record<string, unknown>, signal: AbortSignal) => Promise<IFleetOperation>;
|
|
95
97
|
/** Deploy status, history, a probe now and release state for the local owner (`agl deploy`, `agl release status`). */
|
|
96
98
|
deploy?: (method: TControllerMcpDeployMethod, request: Record<string, unknown>, signal: AbortSignal) => Promise<unknown>;
|
|
99
|
+
/** The host's push settings for the local owner (`agl push`, AGL-1639); each call verifies the owner capability. */
|
|
100
|
+
push?: (method: TControllerMcpPushMethod, request: Record<string, unknown>, signal: AbortSignal) => Promise<unknown>;
|
|
97
101
|
/** A pool's room for new work in AGL's inference proxy, asked of the proxy (AGL-1097); open to every caller. */
|
|
98
102
|
proxyCapacity?: (request: IReq_ControllerMcpProxyCapacity['request'], signal: AbortSignal)
|
|
99
103
|
=> Promise<IReq_ControllerMcpProxyCapacity['response']>;
|
|
@@ -246,6 +250,11 @@ class ControllerMcpBoundedTypedRouter extends plugins.typedrequest.TypedRouter {
|
|
|
246
250
|
// and refuses anything else, an installed older one included. TypedRequest 9 answers `null` where TypedRequest 8
|
|
247
251
|
// returned the `{}` the client sent (an error, a handler that returns nothing), so the host restores it here.
|
|
248
252
|
if (response.response === null) (response as plugins.typedrequestInterfaces.ITypedRequest).response = {};
|
|
253
|
+
if (typeof response.method === 'string' && response.method.startsWith('agl.mcp.push.')
|
|
254
|
+
&& response.request && typeof response.request === 'object') {
|
|
255
|
+
// The owner capability and the push keys never travel back in the echo, including on rejected operations.
|
|
256
|
+
(response as plugins.typedrequestInterfaces.ITypedRequest).request = redactPushRequest(response.request as Record<string, unknown>);
|
|
257
|
+
}
|
|
249
258
|
if (typeof response.method === 'string' && (response.method.startsWith('agl.mcp.configuration.')
|
|
250
259
|
|| response.method.startsWith('agl.mcp.ticket.') || response.method.startsWith('agl.mcp.fleet.') || response.method.startsWith('agl.mcp.deploy.'))) {
|
|
251
260
|
// TypedRequest normally echoes the request. The owner capability must not travel back in
|
|
@@ -304,6 +313,10 @@ const safeTypedResponseError = (
|
|
|
304
313
|
if (methodArg.startsWith('agl.mcp.deploy.') && (deployErrorCodes as readonly unknown[]).includes(code)) {
|
|
305
314
|
return new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 1024), { code });
|
|
306
315
|
}
|
|
316
|
+
// A push refusal's sentence names the field and the rule, never the input (`PushError`).
|
|
317
|
+
if (methodArg.startsWith('agl.mcp.push.') && (pushErrorCodes as readonly unknown[]).includes(code)) {
|
|
318
|
+
return new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 1024), { code });
|
|
319
|
+
}
|
|
307
320
|
if (methodArg.startsWith('agl.mcp.fleet.worker.') && (fleetWorkerErrorCodes as readonly unknown[]).includes(code)) {
|
|
308
321
|
return new plugins.typedrequest.TypedResponseError(errorArg.message.slice(0, 1024), { code });
|
|
309
322
|
}
|
|
@@ -696,6 +709,13 @@ export class ControllerMcpHost {
|
|
|
696
709
|
return this.options.api.deploy(method, request as unknown as Record<string, unknown>, tools?.abortSignal ?? new AbortController().signal) as never;
|
|
697
710
|
})));
|
|
698
711
|
}
|
|
712
|
+
for (const method of controllerMcpPushMethods) {
|
|
713
|
+
routerArg.addTypedHandler(new plugins.typedrequest.TypedHandler<TControllerMcpPushTypedRequest>(method,
|
|
714
|
+
async (request, tools) => run(method, async () => {
|
|
715
|
+
if (!this.options.api.push) throw new Error('Push API is unavailable.');
|
|
716
|
+
return this.options.api.push(method, request as unknown as Record<string, unknown>, tools?.abortSignal ?? new AbortController().signal) as never;
|
|
717
|
+
})));
|
|
718
|
+
}
|
|
699
719
|
routerArg.addTypedHandler(new plugins.typedrequest.TypedHandler<IReq_ControllerMcpProxyCapacity>(
|
|
700
720
|
'agl.mcp.proxy.capacity', async (requestArg, toolsArg) => run('agl.mcp.proxy.capacity', async () => {
|
|
701
721
|
if (!this.options.api.proxyCapacity) throw new Error('Proxy capacity API is unavailable.');
|
|
@@ -28,6 +28,7 @@ import { assertMcpTicketRequest } from './functions.ticketvalidation.js';
|
|
|
28
28
|
import { assertFleetWireRequest } from './fleet/functions.validation.js';
|
|
29
29
|
import { assertSessionFeedWireRequest } from './functions.sessionfeedvalidation.js';
|
|
30
30
|
import { assertFleetDeployWireRequest } from './fleet/functions.deployvalidation.js';
|
|
31
|
+
import { assertPushWireRequest } from './functions.pushwire.js';
|
|
31
32
|
import { isProxyCapacityRequest } from '../ts_interfaces/proxycapacity.js';
|
|
32
33
|
|
|
33
34
|
const maximumIdBytes = 1024;
|
|
@@ -145,6 +146,7 @@ const assertMethodRequest = (
|
|
|
145
146
|
return assertSessionFeedWireRequest(methodArg, requestArg);
|
|
146
147
|
}
|
|
147
148
|
if (methodArg.startsWith('agl.mcp.deploy.')) return assertFleetDeployWireRequest(methodArg, requestArg);
|
|
149
|
+
if (methodArg.startsWith('agl.mcp.push.')) return assertPushWireRequest(methodArg, requestArg);
|
|
148
150
|
if (methodArg === 'agl.mcp.proxy.capacity') {
|
|
149
151
|
if (!isProxyCapacityRequest(requestArg)) throw new Error('Invalid private controller request.');
|
|
150
152
|
return requestArg;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ControllerMcpClient } from './classes.mcpclient.js';
|
|
1
|
+
import { ControllerMcpClient, ControllerMcpClientError } from './classes.mcpclient.js';
|
|
2
2
|
import {
|
|
3
3
|
workerCallerLaunchIdEnvironmentVariable, workerCallerLaunchGenerationEnvironmentVariable,
|
|
4
4
|
type IWorkerCallerReadiness,
|
|
@@ -25,7 +25,13 @@ export class McpWorkerCaller {
|
|
|
25
25
|
if (this.closed) throw new Error('Worker caller enrollment is closed.');
|
|
26
26
|
return this.client.withCaller(response?.credential, undefined, operationArg);
|
|
27
27
|
}
|
|
28
|
-
if (nativeThreadIdArg === undefined)
|
|
28
|
+
if (nativeThreadIdArg === undefined) {
|
|
29
|
+
// Without a launch the controller identifies the bridge by the Claude job its parent runs (AGL-1888). A credential
|
|
30
|
+
// it answers with is the caller, never the one this process inherited; without one the call runs as before.
|
|
31
|
+
const credential = await this.enrollProcess();
|
|
32
|
+
if (this.closed) throw new Error('Worker caller enrollment is closed.');
|
|
33
|
+
return credential === undefined ? operationArg() : this.client.withCaller(credential, undefined, operationArg);
|
|
34
|
+
}
|
|
29
35
|
const response = await this.client.enrollWorker({ nativeThreadId: nativeThreadIdArg, bridgePid: process.pid });
|
|
30
36
|
if (this.closed) throw new Error('Worker caller enrollment is closed.');
|
|
31
37
|
return this.client.withCaller(response.credential, nativeThreadIdArg, operationArg);
|
|
@@ -44,4 +50,20 @@ export class McpWorkerCaller {
|
|
|
44
50
|
public close(): void {
|
|
45
51
|
this.closed = true;
|
|
46
52
|
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The credential the controller answers a process enrollment with, if any. A controller that rejects the request
|
|
56
|
+
* (one older than process enrollment answers HTTP 400, read as `PROTOCOL_MISMATCH`) or fails it (`REQUEST_FAILED`)
|
|
57
|
+
* leaves the bridge as it was; every other failure is the call's own, as it would be without the enrollment.
|
|
58
|
+
*/
|
|
59
|
+
private async enrollProcess(): Promise<string | undefined> {
|
|
60
|
+
try {
|
|
61
|
+
return (await this.client.enrollWorker({ bridgePid: process.pid })).credential;
|
|
62
|
+
} catch (errorArg) {
|
|
63
|
+
if (errorArg instanceof ControllerMcpClientError && (errorArg.code === 'PROTOCOL_MISMATCH' || errorArg.code === 'REQUEST_FAILED')) {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
throw errorArg;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
47
69
|
}
|