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
@@ -1,5 +1,6 @@
1
1
  import * as plugins from '../plugins.js';
2
- import { controllerRuntimeIdKey, type IWorkerClaudeJobRequest, type TWorkerClaudeJobObservation } from '../../ts_interfaces/index.js';
2
+ import { controllerRuntimeIdKey, type IWorkerClaudeJobRequest, type TWorkerClaudeJobObservation, type IWorkerClaudeProcessRequest,
3
+ type TWorkerClaudeProcessIdentification } from '../../ts_interfaces/index.js';
3
4
  import type { IFleetEvent, IFleetWorker, IFleetWorkerProfile, IFleetWorkerJob, IFleetNativeMessageReceipt, TFleetEventKind, TFleetWorkerAction, TFleetWorkerRequest, TFleetWorkerResponse, TFleetWorkerResponseTo, TFleetWorkerJobAction, IFleetWorkerReport, IFleetRelaunchBlocker, IFleetWorkerDispatchHolder, IFleetWorkerSummary, IFleetWorkerSummaryPage } from '../../ts_interfaces/fleetworkers.js';
4
5
  import type { IFleetConfiguration, IFleetOperation, IFleetTicketSync } from '../../ts_interfaces/fleet.js';
5
6
  import type { ITicketActor } from '../../ts_interfaces/tickets.js';
@@ -456,6 +457,63 @@ export class FleetWorkers {
456
457
  return { state: 'unproven', reason: 'the process of its Claude job could not be read' };
457
458
  }
458
459
  }
460
+ /**
461
+ * The reverse of `observeCallerJob`: which worker's Claude background job the process `request.pid` runs, for the
462
+ * controller to identify an MCP bridge that holds no launch by the process it runs under (AGL-1888). Read fresh from
463
+ * the inventories of the fleet's Claude homes (those of its Claude workers that are not archived) and the registry
464
+ * of every owner, on the same one-at-a-time chain. The controller asks only once it proved the process to run an
465
+ * installed Claude Code release.
466
+ */
467
+ public identifyCallerProcess(request: IWorkerClaudeProcessRequest): Promise<TWorkerClaudeProcessIdentification> {
468
+ const task = this.callerJobs.then(() => this.readCallerProcess(request));
469
+ this.callerJobs = task.then(() => undefined, () => undefined);
470
+ return task;
471
+ }
472
+ private async readCallerProcess(request: IWorkerClaudeProcessRequest): Promise<TWorkerClaudeProcessIdentification> {
473
+ const refused = (check: 'parent' | 'inventory' | 'worker', reason: string, forGood: boolean, named: { workerId?: string; nativeSessionId?: string } = {}): TWorkerClaudeProcessIdentification => (
474
+ { state: 'refused', check, reason, forGood, ...named });
475
+ if (this.abort.signal.aborted) return refused('inventory', 'the fleet is closing', false);
476
+ let documents: IFleetWorkerDocument[];
477
+ try { documents = await this.store.list(); }
478
+ catch (error) { return refused('worker', `the fleet registry could not be read (${this.error(error)})`, false); }
479
+ const claude = documents.filter(({ worker }) => worker.harness === 'claude');
480
+ const homes = new Map(claude.filter(({ worker }) => worker.state !== 'archived').map(({ worker }) => [worker.profile.home ?? '', worker.profile.home]));
481
+ if (homes.size === 0) return refused('worker', 'the fleet has no Claude worker', true);
482
+ const listings: Array<{ home: string; agent: IFleetNativeAgent }> = [];
483
+ for (const [key, home] of homes) {
484
+ let agents: IFleetNativeAgent[] | undefined;
485
+ try { agents = await this.backends.claude.inventory?.(home, plugins.os.homedir(), 0); }
486
+ catch (error) { return refused('inventory', `the Claude inventory could not be read (${this.error(error)})`, false); }
487
+ for (const agent of agents ?? []) listings.push({ home: key, agent });
488
+ }
489
+ const listed = listings.filter(({ agent }) => agent.pid === request.pid);
490
+ if (listed.length === 0) {
491
+ // Never an identification: only the reason a bridge one level too deep under a job's process is refused. The
492
+ // controller asks only about a process that runs an installed Claude Code release, and the inventory can still
493
+ // list the process Claude Code just replaced for a job (it retires idle jobs and continues them in a new process),
494
+ // so a process it lists for no session may be listed soon.
495
+ return listings.some(({ agent }) => agent.pid === request.parentPid && agent.kind === 'background')
496
+ ? refused('parent', 'its bridge runs under a child of its Claude job\'s process, not under the job\'s process itself', true)
497
+ : refused('inventory', 'the Claude inventory lists no session in the process its bridge runs under', false);
498
+ }
499
+ if (listed.length > 1) return refused('inventory', 'the Claude inventory lists the process its bridge runs under more than once', false);
500
+ const { home, agent } = listed[0]!;
501
+ if (agent.kind !== 'background' || !agent.id) return refused('inventory', 'the process its bridge runs under is not a Claude background job', true);
502
+ const session = { nativeSessionId: agent.sessionId };
503
+ if (listings.filter((entry) => entry.agent.sessionId === agent.sessionId).length !== 1) {
504
+ return refused('inventory', 'the Claude inventory lists its session more than once', false, session);
505
+ }
506
+ const bound = claude.filter(({ worker }) => worker.nativeId === agent.sessionId);
507
+ const current = bound.filter(({ worker }) => worker.state !== 'archived');
508
+ if (current.length === 0) return refused('worker', bound.length ? 'only an archived fleet worker binds its session' : 'no fleet worker binds its session', true, session);
509
+ if (current.length > 1) return refused('worker', 'more than one fleet worker binds its session', true, session);
510
+ const { owner, worker } = current[0]!, named = { ...session, workerId: worker.id };
511
+ if (worker.lostDispatch) return refused('worker', 'its fleet worker\'s dispatch was resolved as lost', true, named);
512
+ if (worker.pending) return refused('worker', 'its fleet worker has a dispatch in flight', false, named);
513
+ if (worker.state !== 'live') return refused('worker', `its fleet worker is ${worker.state}`, false, named);
514
+ if ((worker.profile.home ?? '') !== home) return refused('worker', 'its fleet worker\'s profile home is not the one whose inventory lists it', true, named);
515
+ return { state: 'identified', workerId: worker.id, projectId: owner, nativeSessionId: agent.sessionId, jobId: agent.id };
516
+ }
459
517
  /** The newest root threads on the host's shared Codex app-server, read at most `maxAgeMs` ago. */
460
518
  public async nativeThreads(maxAgeMs: number): Promise<IFleetNativeThread[]> {
461
519
  return await this.backends.codex.threads?.(plugins.os.homedir(), maxAgeMs) ?? [];
@@ -577,9 +635,11 @@ export class FleetWorkers {
577
635
  }
578
636
  /**
579
637
  * Repairs what follows `worker`'s session after an adoption: a binding that stays on it or was headed to it records
580
- * its error on it and fails the adoption, and a repair that succeeds clears the error an earlier adoption left.
638
+ * its error on it and fails the adoption, and a repair that succeeds clears the error an earlier adoption left. The
639
+ * controller identifies the adopted session's bridge afresh at its next call (AGL-1888).
581
640
  */
582
641
  private async adoptedSessions(owner: string, worker: IFleetWorker): Promise<void> {
642
+ this.options.callers?.adopted();
583
643
  const { stayed, revision } = await this.rebindSessions(owner, { names: [worker.name], own: worker.name,
584
644
  stayed: (failures) => failures.find((failure) => failure.workerName === worker.name) ?? failures.find((failure) => failure.nextName === worker.name) });
585
645
  await this.recordBinding(owner, worker.name, revision, stayed, (current) => {
@@ -818,6 +878,9 @@ export class FleetWorkers {
818
878
  delete current.reconfirmedDispatch; delete current.error; delete current.errorSource;
819
879
  })).worker;
820
880
  this.changed(owner, worker);
881
+ // The worker's caller record proves the bridges of the old session's process: revoked once the registry names
882
+ // the new session, so neither that record nor a process identification of the old session admits them again.
883
+ await this.options.callers?.revoke(worker, 'replacement');
821
884
  }
822
885
  job.workers = [worker];
823
886
  if (this.options.ticketEffects) {
@@ -58,6 +58,8 @@ import {
58
58
  type IDeviceHostDeploys,
59
59
  type IDeviceHostDevice,
60
60
  type IDeviceHostPools,
61
+ type IDeviceHostPush,
62
+ type IDevicePushFailure,
61
63
  type IDeviceHostUnavailable,
62
64
  type IDevicePoolMember,
63
65
  type IDeviceInboxDelta,
@@ -88,6 +90,7 @@ import {
88
90
  type IReq_DeviceHostGet,
89
91
  type IReq_DevicePair,
90
92
  type IReq_DevicePermissionReply,
93
+ type IReq_DevicePushRegister,
91
94
  type IReq_DeviceQuestionReply,
92
95
  type IReq_DeviceSessionRead,
93
96
  type IReq_DeviceSessionSend,
@@ -112,6 +115,7 @@ import { sessionFeedRowId } from './classes.sessionfeed.js';
112
115
  import { directReportReachable, directReportRuntimeId } from './driver/classes.directreports.js';
113
116
  import { DriverError, type DriverService, type IDriverNeedsInput } from './driver/classes.driverservice.js';
114
117
  import { deviceRefusal } from './classes.controllerdevices.js';
118
+ import { isDevicePushToken, type TControllerPushRegistrationState } from './classes.pushregistrations.js';
115
119
  import { controllerFailureJournal } from './classes.failurejournal.js';
116
120
  import { DeployError } from './fleet/classes.deploymonitor.js';
117
121
  import { AglProxyOutdatedError, AglProxyRefusedError, AglProxyUnavailableError } from './classes.proxycontrolclient.js';
@@ -546,12 +550,34 @@ export const deviceHostAgl = (aglArg: {
546
550
  : { kind: 'gateway', state: deviceGatewayStates[aglArg.gateway.state] },
547
551
  });
548
552
 
549
- /** A device's own record as it reads it: no id, key or fingerprint, and nothing it could change. */
550
- export const deviceHostDevice = (deviceArg: IControllerDevice): IDeviceHostDevice => ({
553
+ /**
554
+ * A device's own record as it reads it: no id, key or fingerprint, and nothing it could change; with its push
555
+ * registration while it holds one.
556
+ */
557
+ export const deviceHostDevice = (deviceArg: IControllerDevice, pushArg?: IDeviceHostPush): IDeviceHostDevice => ({
551
558
  name: deviceArg.name,
552
559
  model: deviceArg.model,
553
560
  pairedAt: deviceArg.pairedAt,
554
561
  ...(deviceArg.lastSeenAt === undefined ? {} : { lastSeenAt: deviceArg.lastSeenAt }),
562
+ ...(pushArg === undefined ? {} : { push: pushArg }),
563
+ });
564
+
565
+ /** What the host can send a device on its platform now (AGL-1639). */
566
+ export interface IDevicePushDelivery {
567
+ /** The host's previews setting, one for every device. */
568
+ previews: boolean;
569
+ /** Whether the host holds a credential for the platform that Apple or Google did not refuse. */
570
+ available: boolean;
571
+ /** The device's last notification that did not go out, while none went out after it. */
572
+ lastFailure?: IDevicePushFailure;
573
+ }
574
+
575
+ /** A device's push registration as it reads it: its choice and what the host can send, never its token or salt. */
576
+ export const deviceHostPush = (registrationArg: TControllerPushRegistrationState, deliveryArg: IDevicePushDelivery): IDeviceHostPush => ({
577
+ reports: registrationArg.reports,
578
+ previews: deliveryArg.previews,
579
+ available: deliveryArg.available,
580
+ ...(deliveryArg.lastFailure === undefined ? {} : { lastFailure: { at: deliveryArg.lastFailure.at, reason: deliveryArg.lastFailure.reason } }),
555
581
  });
556
582
 
557
583
  /**
@@ -1413,6 +1439,30 @@ export const assertDeviceDirectReportMessageRequest = (valueArg: unknown): IReq_
1413
1439
  return { name, text };
1414
1440
  };
1415
1441
 
1442
+ /**
1443
+ * A device's push registration, in shape: the platform's token, the APNs environment exactly for an APNs token, and
1444
+ * the choice of reports. No refusal repeats the token.
1445
+ */
1446
+ export const assertDevicePushRegisterRequest = (valueArg: unknown): IReq_DevicePushRegister['request'] => {
1447
+ const value = assertObject(valueArg, 'device push register request');
1448
+ assertKeys(value, ['platform', 'token', 'reports'], ['environment']);
1449
+ if (value.platform !== 'apns' && value.platform !== 'fcm') throw new Error('platform must be apns or fcm.');
1450
+ if (!isDevicePushToken(value.platform, value.token)) {
1451
+ throw new Error(value.platform === 'apns'
1452
+ ? 'token must be an APNs device token: lowercase hex of 32 to 100 bytes.'
1453
+ : 'token must be an FCM registration token: 1 to 1024 characters of letters, digits, _, - and :.');
1454
+ }
1455
+ if (typeof value.reports !== 'boolean') throw new Error('reports must be true or false.');
1456
+ if (value.platform === 'fcm') {
1457
+ if (value.environment !== undefined) throw new Error('environment is for an APNs token only.');
1458
+ return { platform: 'fcm', token: value.token, reports: value.reports };
1459
+ }
1460
+ if (value.environment !== 'sandbox' && value.environment !== 'production') {
1461
+ throw new Error('environment must be sandbox or production for an APNs token.');
1462
+ }
1463
+ return { platform: 'apns', token: value.token, environment: value.environment, reports: value.reports };
1464
+ };
1465
+
1416
1466
  /** A direct child's OpenCode session id, as the Inbox names it. */
1417
1467
  const assertChildSessionId = (valueArg: unknown): string => {
1418
1468
  const id = assertText(valueArg, 'childSessionId', 512);
@@ -45,6 +45,7 @@ const placementText = (accountArg: NonNullable<TReportedProxyStatus['accounts']>
45
45
  if (accountArg.lifecycle === undefined) return '';
46
46
  if (accountArg.lifecycle === 'lapsed') return `; lapsed ${accountArg.lapsesAt}, never routed to again`;
47
47
  return `${accountArg.lifecycle === 'canceled' ? `; canceled, lapses ${accountArg.lapsesAt}` : ''}`
48
+ + `${accountArg.priorityUntil ? `; priority until ${accountArg.priorityUntil} (set by the owner)` : ''}`
48
49
  + `${accountArg.renewal ? `; renews ${accountArg.renewal.at} (set by the owner`
49
50
  + `${accountArg.lifecycle === 'canceled' ? ', ignored while it lapses' : ''})` : ''}`
50
51
  + `; placement ${scoreText(accountArg.placementScore ?? null)}`
@@ -0,0 +1,212 @@
1
+ import { ControllerMcpClient } from './classes.mcpclient.js';
2
+ import { withCliDiagnostics } from './functions.clidiagnostics.js';
3
+ import { withLocalConfigurationOwner } from './functions.configurationowner.js';
4
+ import { readStandardInputSecret } from './functions.remotecli.js';
5
+ import { defaultControllerPort } from './classes.config.js';
6
+ import { pushClockSkewText, pushTestAnswerWaitMs, type IPushChange, type IPushFailureStatus, type IPushStatus, type IPushTestResult, type TPushOperation } from '../ts_interfaces/push.js';
7
+
8
+ export const pushCliHelp = `Usage: agl push status [--json]
9
+ agl push apns set --key-id KEY_ID --team-id TEAM_ID [--topic BUNDLE_ID] < AuthKey_KEY_ID.p8
10
+ agl push apns unset
11
+ agl push fcm set < SERVICE_ACCOUNT.json
12
+ agl push fcm unset
13
+ agl push previews on|off
14
+ agl push test [--device DEVICE_ID] [--json]
15
+ Notifications of what waits in the Inbox go from this host straight to Apple's (APNs) and Google's (FCM) push
16
+ services, to the paired devices that registered for them. Every command accepts --port PORT (default 4097), runs
17
+ against the running controller as the local owner, and every change is audited.
18
+ apns set reads the AuthKey .p8 file Apple issued for the team (a key with Apple Push Notifications service) from
19
+ standard input, never from a terminal. --key-id is the key's 10-character id, --team-id the team's; the
20
+ topic is the app's bundle id, com.modelprofile.harness unless --topic names another.
21
+ fcm set reads the JSON key file of the Firebase project's service account (Project settings, Service accounts,
22
+ Generate new private key) from standard input, never from a terminal. Its token_uri is ignored: the host
23
+ asks Google's own endpoints only.
24
+ Both keys are sealed with the TPM and never printed. Set one again to replace it, also after Apple or Google
25
+ refused it: nothing is sent on a refused credential.
26
+ unset removes the platform's credential: nothing is sent on it until it is set again; the devices stay registered.
27
+ previews on: a notification also says where an item lives, what it asks and its id, which Apple or Google can read.
28
+ off (the default): it says one fixed sentence per kind of item.
29
+ status previews, and for each platform: whether its credential is set and usable, what it is for (key id, team id
30
+ and topic; project and service account), when it was set, the registered devices, why Apple or Google
31
+ refused it, and the last send that failed since the controller started (with how far the host's clock is off
32
+ when Google refused for it). --json prints the answer as JSON.
33
+ test sends the test notification ("Push from AGL works.") to every registered device, or to the one --device
34
+ names (its id, as Settings -> Devices shows it), and prints what Apple or Google answered for each: delivered,
35
+ or why not. A device whose token the push service no longer knows loses its registration; the app registers
36
+ again on its next connect. --json prints the answer as JSON.
37
+ `;
38
+
39
+ export type TPushCliArguments = { port: number; json: boolean } & (
40
+ | { operation: 'status' }
41
+ | { operation: 'apns.set'; keyId: string; teamId: string; topic?: string }
42
+ | { operation: 'apns.unset' }
43
+ | { operation: 'fcm.set' }
44
+ | { operation: 'fcm.unset' }
45
+ | { operation: 'previews'; previews: boolean }
46
+ | { operation: 'test'; deviceId?: string }
47
+ );
48
+
49
+ /** `agl push …`: the operation and its options; a usage error names the option, never a value it does not know. */
50
+ export const parsePushCliArguments = (argsArg: readonly string[]): TPushCliArguments => {
51
+ const rest = [...argsArg];
52
+ const first = rest.shift();
53
+ let operation: TPushOperation | undefined;
54
+ let previews: boolean | undefined;
55
+ if (first === 'status' || first === 'test') operation = first;
56
+ else if ((first === 'apns' || first === 'fcm') && (rest[0] === 'set' || rest[0] === 'unset')) operation = `${first}.${rest.shift() as 'set' | 'unset'}`;
57
+ else if (first === 'previews' && (rest[0] === 'on' || rest[0] === 'off')) {
58
+ operation = 'previews';
59
+ previews = rest.shift() === 'on';
60
+ }
61
+ if (!operation) throw new Error(pushCliHelp);
62
+ const allowed = new Set(['--port', ...(operation === 'status' || operation === 'test' ? ['--json'] : []),
63
+ ...(operation === 'apns.set' ? ['--key-id', '--team-id', '--topic'] : []), ...(operation === 'test' ? ['--device'] : [])]);
64
+ const options = new Map<string, string>();
65
+ for (let index = 0; index < rest.length; index++) {
66
+ const token = rest[index]!;
67
+ const equals = token.startsWith('--') ? token.indexOf('=') : -1;
68
+ const flag = equals > 0 ? token.slice(0, equals) : token;
69
+ if (!flag.startsWith('--')) throw new Error(`Unexpected argument for agl push: ${flag.slice(0, 64)}`);
70
+ if (!allowed.has(flag)) throw new Error(`Unknown push option: ${flag.slice(0, 64)}.`);
71
+ if (options.has(flag)) throw new Error(`Duplicate push option: ${flag}.`);
72
+ if (flag === '--json') {
73
+ if (equals > 0) throw new Error('--json takes no value.');
74
+ options.set(flag, 'true');
75
+ continue;
76
+ }
77
+ const value = equals > 0 ? token.slice(equals + 1) : rest[++index];
78
+ if (value === undefined || value === '' || (equals < 0 && value.startsWith('--'))) throw new Error(`${flag} requires a value.`);
79
+ options.set(flag, value);
80
+ }
81
+ const port = options.has('--port') ? Number(options.get('--port')) : defaultControllerPort;
82
+ if (!/^[1-9][0-9]{0,4}$/u.test(String(port)) || port > 65_535) throw new Error('--port must be an integer between 1 and 65535.');
83
+ const base = { port, json: options.has('--json') };
84
+ if (operation === 'apns.set') {
85
+ const keyId = options.get('--key-id');
86
+ const teamId = options.get('--team-id');
87
+ if (keyId === undefined) throw new Error('agl push apns set requires --key-id.');
88
+ if (teamId === undefined) throw new Error('agl push apns set requires --team-id.');
89
+ const topic = options.get('--topic');
90
+ return { ...base, operation, keyId, teamId, ...(topic === undefined ? {} : { topic }) };
91
+ }
92
+ if (operation === 'previews') return { ...base, operation, previews: previews! };
93
+ if (operation === 'test') {
94
+ const deviceId = options.get('--device');
95
+ return { ...base, operation, ...(deviceId === undefined ? {} : { deviceId }) };
96
+ }
97
+ return { ...base, operation };
98
+ };
99
+
100
+ const platformName = { apns: 'APNs', fcm: 'FCM' } as const;
101
+
102
+ const time = (valueArg: number): string => new Date(valueArg).toISOString();
103
+
104
+ const failureLine = (failureArg: IPushFailureStatus): string => (
105
+ `${failureArg.reason}${failureArg.vendorReason === undefined ? '' : ` (${failureArg.vendorReason})`} at ${time(failureArg.at)}`
106
+ + (failureArg.clockSkewMs === undefined ? ''
107
+ : `; the push service's clock and the host's were ${pushClockSkewText(failureArg.clockSkewMs)}: set the host's clock right (NTP)`)
108
+ );
109
+
110
+ const devices = (countArg: number): string => `${countArg} registered device${countArg === 1 ? '' : 's'}`;
111
+
112
+ /** One device's answer to `agl push test`, as a line: never its token. */
113
+ export const pushTestLine = (resultArg: IPushTestResult): string => {
114
+ const where = `${resultArg.name} (${resultArg.deviceId}, ${platformName[resultArg.platform]}${resultArg.environment === undefined ? '' : ` ${resultArg.environment}`})`;
115
+ const vendor = resultArg.vendorReason === undefined ? '' : ` (${resultArg.vendorReason})`;
116
+ if (resultArg.outcome === 'delivered') return `${where}: delivered`;
117
+ if (resultArg.outcome === 'unregistered') {
118
+ return `${where}: the push service no longer knows its token${vendor}; its registration was removed, and the app registers again on its next connect`;
119
+ }
120
+ if (resultArg.outcome === 'unavailable') return `${where}: not sent: the host holds no usable ${platformName[resultArg.platform]} credential`;
121
+ if (resultArg.outcome === 'no_answer') return `${where}: no answer in time: ${platformName[resultArg.platform]} did not answer within ${pushTestAnswerWaitMs / 1000} s; the notification may still arrive`;
122
+ return `${where}: not delivered: ${resultArg.outcome}${vendor}`;
123
+ };
124
+
125
+ /** `agl push status` as lines: previews, then each platform. */
126
+ export const pushStatusLines = (statusArg: IPushStatus): string[] => {
127
+ const lines = [`Previews: ${statusArg.previews ? 'on' : 'off'}`];
128
+ const { apns, fcm } = statusArg;
129
+ const states = {
130
+ unset: 'not set',
131
+ ready: 'ready',
132
+ refused: 'refused: nothing is sent until it is set again',
133
+ unreadable: 'unreadable on this machine: nothing is sent until it is set again',
134
+ } as const;
135
+ lines.push(`APNs: ${states[apns.state]}${apns.keyId === undefined ? '' : `, key id ${apns.keyId}, team ${apns.teamId}, topic ${apns.topic}`}`
136
+ + `${apns.setAt === undefined ? '' : `, set ${time(apns.setAt)}`}; ${devices(apns.registrations)}`);
137
+ if (apns.refused) lines.push(` refused ${failureLine(apns.refused)}`);
138
+ if (apns.lastFailure) lines.push(` last failed send: ${failureLine(apns.lastFailure)}`);
139
+ lines.push(`FCM: ${states[fcm.state]}${fcm.projectId === undefined ? '' : `, project ${fcm.projectId}, service account ${fcm.clientEmail}`}`
140
+ + `${fcm.setAt === undefined ? '' : `, set ${time(fcm.setAt)}`}; ${devices(fcm.registrations)}`);
141
+ if (fcm.refused) lines.push(` refused ${failureLine(fcm.refused)}`);
142
+ if (fcm.lastFailure) lines.push(` last failed send: ${failureLine(fcm.lastFailure)}`);
143
+ return lines;
144
+ };
145
+
146
+ /** What a change did, as one line. */
147
+ const changeLine = (parsedArg: TPushCliArguments, changeArg: IPushChange): string => {
148
+ if (parsedArg.operation === 'apns.set') {
149
+ const { keyId, teamId, topic } = changeArg.status.apns;
150
+ return `Set the APNs credential: key id ${keyId}, team ${teamId}, topic ${topic}. The key is sealed with the TPM and never printed.`;
151
+ }
152
+ if (parsedArg.operation === 'fcm.set') {
153
+ const { projectId, clientEmail } = changeArg.status.fcm;
154
+ return `Set the FCM credential: project ${projectId}, service account ${clientEmail}. The key is sealed with the TPM and never printed.`;
155
+ }
156
+ if (parsedArg.operation === 'apns.unset' || parsedArg.operation === 'fcm.unset') {
157
+ const name = platformName[parsedArg.operation === 'apns.unset' ? 'apns' : 'fcm'];
158
+ return changeArg.changed ? `Removed the ${name} credential: nothing is sent on ${name} until it is set again.`
159
+ : `No ${name} credential was set; nothing changed.`;
160
+ }
161
+ const previews = (parsedArg as { previews: boolean }).previews ? 'on' : 'off';
162
+ return changeArg.changed ? `Previews are ${previews} now.` : `Previews were ${previews} already; nothing changed.`;
163
+ };
164
+
165
+ export interface IPushCliOptions {
166
+ /** Where `apns set` and `fcm set` read their key; this process's standard input when absent. */
167
+ input?: NodeJS.ReadableStream & { isTTY?: boolean };
168
+ /** Where the outcome is written; standard output when absent. */
169
+ write?: (textArg: string) => void;
170
+ /** Runs an operation with the local owner capability; `withLocalConfigurationOwner` when absent. For tests. */
171
+ withOwner?: <T>(clientArg: ControllerMcpClient, portArg: number, operationArg: (ownerTokenArg: string) => Promise<T>) => Promise<T>;
172
+ }
173
+
174
+ /** The key a `set` reads, refused from a terminal; nothing of it is printed. */
175
+ const readKey = (parsedArg: TPushCliArguments, inputArg: NodeJS.ReadableStream & { isTTY?: boolean }): Promise<string> => (
176
+ parsedArg.operation === 'apns.set'
177
+ ? readStandardInputSecret(inputArg, 'agl push apns set reads the AuthKey .p8 file from a pipe or a file, never from a '
178
+ + 'terminal: run it as `agl push apns set --key-id KEY_ID --team-id TEAM_ID < AuthKey_KEY_ID.p8`.', 'an APNs signing key')
179
+ : readStandardInputSecret(inputArg, 'agl push fcm set reads the service account key file from a pipe or a file, never '
180
+ + 'from a terminal: run it as `agl push fcm set < SERVICE_ACCOUNT.json`.', 'a service account key file', 16 * 1024)
181
+ );
182
+
183
+ export const runPushCli = async (argsArg: string[], optionsArg: IPushCliOptions = {}): Promise<void> => {
184
+ const write = optionsArg.write ?? ((textArg: string) => { process.stdout.write(textArg); });
185
+ if (argsArg.includes('--help') || argsArg.includes('-h')) { write(pushCliHelp); return; }
186
+ const parsed = parsePushCliArguments(argsArg);
187
+ const key = parsed.operation === 'apns.set' || parsed.operation === 'fcm.set'
188
+ ? await readKey(parsed, optionsArg.input ?? process.stdin) : undefined;
189
+ const request = parsed.operation === 'apns.set'
190
+ ? { keyId: parsed.keyId, teamId: parsed.teamId, ...(parsed.topic === undefined ? {} : { topic: parsed.topic }), signingKey: key! }
191
+ : parsed.operation === 'fcm.set' ? { serviceAccount: key! }
192
+ : parsed.operation === 'previews' ? { previews: parsed.previews }
193
+ : parsed.operation === 'test' && parsed.deviceId !== undefined ? { deviceId: parsed.deviceId } : {};
194
+ const client = new ControllerMcpClient({ controllerPort: parsed.port });
195
+ const withOwner = optionsArg.withOwner ?? withLocalConfigurationOwner;
196
+ await withCliDiagnostics(async () => withOwner(client, parsed.port, async (ownerTokenArg) => {
197
+ const answer = await client.push(parsed.operation, { ...request, ownerToken: ownerTokenArg } as never);
198
+ if (parsed.operation === 'status') {
199
+ write(parsed.json ? `${JSON.stringify(answer)}\n` : pushStatusLines(answer as IPushStatus).map((lineArg) => `${lineArg}\n`).join(''));
200
+ return;
201
+ }
202
+ if (parsed.operation === 'test') {
203
+ const { results } = answer as { results: IPushTestResult[] };
204
+ write(parsed.json ? `${JSON.stringify(answer)}\n`
205
+ : results.length === 0 ? 'No paired device is registered for notifications.\n'
206
+ : results.map((resultArg) => `${pushTestLine(resultArg)}\n`).join(''));
207
+ return;
208
+ }
209
+ const change = answer as IPushChange;
210
+ write([changeLine(parsed, change), ...pushStatusLines(change.status)].map((lineArg) => `${lineArg}\n`).join(''));
211
+ }));
212
+ };
@@ -0,0 +1,129 @@
1
+ import * as plugins from './plugins.js';
2
+ import type { TPushErrorCode } from '../ts_interfaces/push.js';
3
+
4
+ /**
5
+ * The push credentials the owner gives the host (AGL-1639), checked before they are sealed: an APNs signing key
6
+ * (Apple's AuthKey .p8 file: one P-256 private key) with its key id, team id and topic, and an FCM service account key
7
+ * (Google's JSON key file: a project, the service account's address and an RSA private key). A refusal names the field
8
+ * and the rule, never what was given.
9
+ */
10
+
11
+ /** The bundle id the AGL apps ship under (iOS and Android): the APNs topic unless the owner names another. */
12
+ export const defaultApnsTopic = 'com.modelprofile.harness';
13
+
14
+ /** A refusal of an `agl push` request, with the sentence the owner reads. */
15
+ export class PushError extends Error {
16
+ constructor(public readonly code: TPushErrorCode, messageArg: string) {
17
+ super(messageArg);
18
+ this.name = 'PushError';
19
+ }
20
+ }
21
+
22
+ /** An Apple key id or team id: 10 characters of capital letters and digits. */
23
+ const appleIdPattern = /^[A-Z0-9]{10}$/u;
24
+ /** A bundle id: at least two dot-separated parts of letters, digits and hyphens, at most 155 characters. */
25
+ const bundleIdPattern = /^(?=.{3,155}$)[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/u;
26
+ /** A Google Cloud project id: 6 to 30 lowercase letters, digits and hyphens, from a letter, not ending in a hyphen. */
27
+ const projectIdPattern = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/u;
28
+ /** A service account's address: one line of printable ASCII around one `@`, at most 254 characters. */
29
+ const clientEmailPattern = /^(?=.{3,254}$)[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/u;
30
+ /** The id of a service account key, which Google names in the JWT header (`kid`). */
31
+ const privateKeyIdPattern = /^[A-Za-z0-9]{1,128}$/u;
32
+
33
+ export const isAppleId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && appleIdPattern.test(valueArg);
34
+ export const isBundleId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && bundleIdPattern.test(valueArg);
35
+ export const isFirebaseProjectId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && projectIdPattern.test(valueArg);
36
+ export const isServiceAccountEmail = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && clientEmailPattern.test(valueArg);
37
+ export const isServiceAccountKeyId = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && privateKeyIdPattern.test(valueArg);
38
+
39
+ const refuse = (messageArg: string): PushError => new PushError('push_credential_invalid', messageArg);
40
+
41
+ /** A private key from PEM text; refused, without the cause (which could quote the input), when it is none. */
42
+ const readPrivateKey = (pemArg: string, refusalArg: string): plugins.crypto.KeyObject => {
43
+ try {
44
+ return plugins.crypto.createPrivateKey({ key: pemArg, format: 'pem' });
45
+ } catch {
46
+ throw refuse(refusalArg);
47
+ }
48
+ };
49
+
50
+ /** A private key as the store keeps it sealed: PKCS #8, DER. */
51
+ export const privateKeyBytes = (keyArg: plugins.crypto.KeyObject): Buffer => keyArg.export({ format: 'der', type: 'pkcs8' });
52
+
53
+ /** A sealed key read back. */
54
+ export const privateKeyFromBytes = (bytesArg: Uint8Array): plugins.crypto.KeyObject => (
55
+ plugins.crypto.createPrivateKey({ key: Buffer.from(bytesArg), format: 'der', type: 'pkcs8' })
56
+ );
57
+
58
+ export interface IApnsCredentialInput {
59
+ keyId: string;
60
+ teamId: string;
61
+ topic: string;
62
+ key: plugins.crypto.KeyObject;
63
+ }
64
+
65
+ /** Whether a key is a P-256 private key, the only kind APNs signs provider tokens with (ES256). */
66
+ export const isApnsSigningKey = (keyArg: plugins.crypto.KeyObject): boolean => (
67
+ keyArg.type === 'private' && keyArg.asymmetricKeyType === 'ec' && keyArg.asymmetricKeyDetails?.namedCurve === 'prime256v1'
68
+ );
69
+
70
+ /** Whether a key is an RSA private key of at least 2048 bits, which Google's token endpoint takes (RS256). */
71
+ export const isServiceAccountSigningKey = (keyArg: plugins.crypto.KeyObject): boolean => (
72
+ keyArg.type === 'private' && keyArg.asymmetricKeyType === 'rsa' && (keyArg.asymmetricKeyDetails?.modulusLength ?? 0) >= 2048
73
+ );
74
+
75
+ /** `agl push apns set`: the key id, team id and topic, and the .p8 file's text. */
76
+ export const parseApnsCredential = (inputArg: { keyId: unknown; teamId: unknown; topic?: unknown; signingKey: unknown }): IApnsCredentialInput => {
77
+ if (!isAppleId(inputArg.keyId)) throw refuse('--key-id must be the 10-character key id Apple shows for the key: capital letters and digits.');
78
+ if (!isAppleId(inputArg.teamId)) throw refuse('--team-id must be the 10-character Apple team id: capital letters and digits.');
79
+ const topic = inputArg.topic ?? defaultApnsTopic;
80
+ if (!isBundleId(topic)) throw refuse('--topic must be the app\'s bundle id, such as com.modelprofile.harness.');
81
+ const refusal = 'The standard input is not an APNs signing key: give the AuthKey .p8 file Apple issued, which holds one '
82
+ + 'P-256 private key (PKCS #8 PEM).';
83
+ if (typeof inputArg.signingKey !== 'string' || inputArg.signingKey.length === 0) throw refuse(refusal);
84
+ const key = readPrivateKey(inputArg.signingKey, refusal);
85
+ if (!isApnsSigningKey(key)) throw refuse(refusal);
86
+ return { keyId: inputArg.keyId, teamId: inputArg.teamId, topic, key };
87
+ };
88
+
89
+ export interface IFcmCredentialInput {
90
+ projectId: string;
91
+ clientEmail: string;
92
+ /** The key's id, when the file names one: the provider token's `kid`. */
93
+ privateKeyId?: string;
94
+ key: plugins.crypto.KeyObject;
95
+ }
96
+
97
+ /**
98
+ * `agl push fcm set`: the service account key file's JSON. Its `token_uri` and the other URLs it carries are ignored:
99
+ * the host asks Google's own token endpoint only.
100
+ */
101
+ export const parseFcmCredential = (textArg: unknown): IFcmCredentialInput => {
102
+ const file = 'The standard input is not a service account key: give the JSON key file of the Firebase project\'s service '
103
+ + 'account (Project settings, Service accounts, Generate new private key).';
104
+ if (typeof textArg !== 'string' || textArg.length === 0) throw refuse(file);
105
+ let value: unknown;
106
+ try {
107
+ value = JSON.parse(textArg);
108
+ } catch {
109
+ throw refuse(file);
110
+ }
111
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw refuse(file);
112
+ const record = value as Record<string, unknown>;
113
+ if (record.type !== 'service_account') throw refuse(`${file} Its type is not service_account.`);
114
+ if (!isFirebaseProjectId(record.project_id)) throw refuse('The service account key has no valid project_id.');
115
+ if (!isServiceAccountEmail(record.client_email)) throw refuse('The service account key has no valid client_email.');
116
+ if (record.private_key_id !== undefined && !isServiceAccountKeyId(record.private_key_id)) {
117
+ throw refuse('The service account key has an invalid private_key_id.');
118
+ }
119
+ const keyRefusal = 'The service account key\'s private_key is not an RSA private key of at least 2048 bits (PKCS #8 PEM).';
120
+ if (typeof record.private_key !== 'string' || record.private_key.length === 0) throw refuse(keyRefusal);
121
+ const key = readPrivateKey(record.private_key, keyRefusal);
122
+ if (!isServiceAccountSigningKey(key)) throw refuse(keyRefusal);
123
+ return {
124
+ projectId: record.project_id,
125
+ clientEmail: record.client_email,
126
+ ...(record.private_key_id === undefined ? {} : { privateKeyId: record.private_key_id }),
127
+ key,
128
+ };
129
+ };
@@ -0,0 +1,106 @@
1
+ import {
2
+ controllerMcpPushMethods,
3
+ pushOperationOf,
4
+ pushSecretRequestFields,
5
+ type TControllerMcpPushMethod,
6
+ type TPushOperation,
7
+ } from '../ts_interfaces/push.js';
8
+
9
+ /**
10
+ * The shape of `agl push` requests and answers on the controller's private channel (AGL-1639). Only the shape: the
11
+ * controller judges the values, and neither a refusal here nor one there repeats a value, since `signingKey` and
12
+ * `serviceAccount` carry the owner's keys.
13
+ */
14
+
15
+ const isRecord = (valueArg: unknown): valueArg is Record<string, unknown> => (
16
+ !!valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg)
17
+ );
18
+
19
+ const isText = (valueArg: unknown, maximumArg: number): valueArg is string => (
20
+ typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= maximumArg
21
+ );
22
+
23
+ /** Each request's fields besides `ownerToken`, with the most a field may hold. */
24
+ const requestFields: Record<TPushOperation, { required: Record<string, number | 'boolean'>; optional?: Record<string, number> }> = {
25
+ status: { required: {} },
26
+ // A .p8 file is about 250 bytes; a service account key file about 2.4 KB.
27
+ 'apns.set': { required: { keyId: 64, teamId: 64, signingKey: 16 * 1024 }, optional: { topic: 255 } },
28
+ 'apns.unset': { required: {} },
29
+ 'fcm.set': { required: { serviceAccount: 32 * 1024 } },
30
+ 'fcm.unset': { required: {} },
31
+ previews: { required: { previews: 'boolean' } },
32
+ test: { required: {}, optional: { deviceId: 64 } },
33
+ };
34
+
35
+ export const isControllerMcpPushMethod = (methodArg: string): methodArg is TControllerMcpPushMethod => (
36
+ (controllerMcpPushMethods as readonly string[]).includes(methodArg)
37
+ );
38
+
39
+ /** An `agl.mcp.push.*` request in shape, with the owner capability; refused without naming a value. */
40
+ export const assertPushWireRequest = (methodArg: string, valueArg: unknown): Record<string, unknown> => {
41
+ if (!isControllerMcpPushMethod(methodArg) || !isRecord(valueArg)) throw new Error('Invalid private controller request.');
42
+ const { required, optional = {} } = requestFields[pushOperationOf(methodArg)];
43
+ const keys = Object.keys(valueArg);
44
+ if (!isText(valueArg.ownerToken, 1024)
45
+ || keys.some((keyArg) => keyArg !== 'ownerToken' && !Object.hasOwn(required, keyArg) && !Object.hasOwn(optional, keyArg))
46
+ || Object.entries(required).some(([keyArg, ruleArg]) => (ruleArg === 'boolean'
47
+ ? typeof valueArg[keyArg] !== 'boolean' : !isText(valueArg[keyArg], ruleArg)))
48
+ || Object.entries(optional).some(([keyArg, maximumArg]) => valueArg[keyArg] !== undefined && !isText(valueArg[keyArg], maximumArg))) {
49
+ throw new Error('Invalid private controller request.');
50
+ }
51
+ return valueArg;
52
+ };
53
+
54
+ /** A request as the controller's answer echoes it: the owner capability and the keys replaced. */
55
+ export const redactPushRequest = (requestArg: Record<string, unknown>): Record<string, unknown> => {
56
+ const redacted = { ...requestArg };
57
+ for (const field of ['ownerToken', ...pushSecretRequestFields]) if (Object.hasOwn(redacted, field)) redacted[field] = '[redacted]';
58
+ return redacted;
59
+ };
60
+
61
+ const credentialStates: readonly unknown[] = ['unset', 'ready', 'refused', 'unreadable'];
62
+ const failureReasons: readonly unknown[] = ['credential_refused', 'refused', 'rate_limited', 'service_failed', 'unreachable'];
63
+
64
+ const isTime = (valueArg: unknown): boolean => Number.isSafeInteger(valueArg) && (valueArg as number) > 0;
65
+
66
+ /** A clock skew within a year either way. */
67
+ const isClockSkew = (valueArg: unknown): boolean => Number.isSafeInteger(valueArg) && Math.abs(valueArg as number) <= 366 * 24 * 60 * 60_000;
68
+
69
+ const isFailure = (valueArg: unknown): boolean => isRecord(valueArg) && isTime(valueArg.at) && failureReasons.includes(valueArg.reason)
70
+ && (valueArg.vendorReason === undefined || isText(valueArg.vendorReason, 64))
71
+ && (valueArg.clockSkewMs === undefined || isClockSkew(valueArg.clockSkewMs))
72
+ && Object.keys(valueArg).every((keyArg) => ['at', 'reason', 'vendorReason', 'clockSkewMs'].includes(keyArg));
73
+
74
+ const isPlatformStatus = (valueArg: unknown, fieldsArg: readonly string[]): boolean => isRecord(valueArg)
75
+ && credentialStates.includes(valueArg.state)
76
+ && Number.isSafeInteger(valueArg.registrations) && (valueArg.registrations as number) >= 0
77
+ && (valueArg.setAt === undefined || isTime(valueArg.setAt))
78
+ && (valueArg.refused === undefined || isFailure(valueArg.refused))
79
+ && (valueArg.lastFailure === undefined || isFailure(valueArg.lastFailure))
80
+ && fieldsArg.every((keyArg) => valueArg[keyArg] === undefined || isText(valueArg[keyArg], 255))
81
+ && Object.keys(valueArg).every((keyArg) => ['state', 'registrations', 'setAt', 'refused', 'lastFailure', ...fieldsArg].includes(keyArg));
82
+
83
+ const isPushStatus = (valueArg: unknown): boolean => isRecord(valueArg)
84
+ && Object.keys(valueArg).length === 3 && typeof valueArg.previews === 'boolean'
85
+ && isPlatformStatus(valueArg.apns, ['keyId', 'teamId', 'topic'])
86
+ && isPlatformStatus(valueArg.fcm, ['projectId', 'clientEmail']);
87
+
88
+ const testOutcomes: readonly unknown[] = ['delivered', 'unregistered', 'unavailable', 'no_answer', ...failureReasons];
89
+
90
+ const isTestResult = (valueArg: unknown): boolean => isRecord(valueArg)
91
+ && isText(valueArg.deviceId, 64) && typeof valueArg.name === 'string' && valueArg.name.length <= 256
92
+ && (valueArg.platform === 'apns' || valueArg.platform === 'fcm')
93
+ && (valueArg.environment === undefined || valueArg.environment === 'sandbox' || valueArg.environment === 'production')
94
+ && testOutcomes.includes(valueArg.outcome)
95
+ && (valueArg.vendorReason === undefined || isText(valueArg.vendorReason, 64))
96
+ && Object.keys(valueArg).every((keyArg) => ['deviceId', 'name', 'platform', 'environment', 'outcome', 'vendorReason'].includes(keyArg));
97
+
98
+ /** An `agl.mcp.push.*` answer in shape, as `agl push` prints it. */
99
+ export const assertPushResponse = (methodArg: TControllerMcpPushMethod, valueArg: unknown): void => {
100
+ const operation = pushOperationOf(methodArg);
101
+ const valid = operation === 'status' ? isPushStatus(valueArg)
102
+ : operation === 'test' ? isRecord(valueArg) && Object.keys(valueArg).length === 1 && Array.isArray(valueArg.results)
103
+ && valueArg.results.length <= 1024 && valueArg.results.every(isTestResult)
104
+ : isRecord(valueArg) && Object.keys(valueArg).length === 2 && typeof valueArg.changed === 'boolean' && isPushStatus(valueArg.status);
105
+ if (!valid) throw new Error('invalid');
106
+ };