agl 43.1.0 → 43.2.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 +12 -0
- package/dist_serve/bundle.js +5329 -5116
- package/dist_serve/bundle.js.map +2 -2
- package/dist_serve/bundle.js.third-party-notices.json +30 -30
- package/dist_serve/bundle.js.third-party-notices.txt +30 -30
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/aglapi/aglapisurface.document.js +325 -1
- package/dist_ts/aglapi/interfaces.d.ts +3 -0
- package/dist_ts/aglapi/interfaces.js +2 -1
- package/dist_ts/classes.authmodels.js +17 -4
- package/dist_ts/classes.authstore.js +16 -2
- package/dist_ts/classes.cli.d.ts +4 -2
- package/dist_ts/classes.cli.js +6 -3
- package/dist_ts/classes.controller.d.ts +10 -0
- package/dist_ts/classes.controller.js +119 -4
- package/dist_ts/classes.controllermanagement.d.ts +14 -4
- package/dist_ts/classes.controllermanagement.js +20 -2
- package/dist_ts/classes.gatewayclient.d.ts +115 -0
- package/dist_ts/classes.gatewayclient.js +336 -0
- package/dist_ts/classes.gatewayclientstore.d.ts +97 -0
- package/dist_ts/classes.gatewayclientstore.js +261 -0
- package/dist_ts/classes.inferencerouter.d.ts +9 -0
- package/dist_ts/classes.inferencerouter.js +11 -1
- package/dist_ts/classes.inferenceservice.d.ts +9 -0
- package/dist_ts/classes.inferenceservice.js +27 -1
- package/dist_ts/classes.mcpclient.d.ts +4 -1
- package/dist_ts/classes.mcpclient.js +19 -1
- package/dist_ts/classes.mcpcontrollerhost.d.ts +3 -1
- package/dist_ts/classes.mcpcontrollerhost.js +9 -1
- package/dist_ts/classes.mcptools.d.ts +3 -3
- package/dist_ts/classes.mcptools.js +26 -1
- package/dist_ts/classes.mcpvalidation.js +7 -1
- package/dist_ts/classes.proxycontrol.d.ts +11 -0
- package/dist_ts/classes.proxycontrol.js +7 -1
- package/dist_ts/classes.proxycontrolclient.d.ts +17 -0
- package/dist_ts/classes.proxycontrolclient.js +35 -1
- package/dist_ts/classes.proxydaemon.js +8 -1
- package/dist_ts/classes.proxymonitor.d.ts +7 -0
- package/dist_ts/classes.proxymonitor.js +13 -1
- package/dist_ts/classes.trustedproxysecrets.d.ts +2 -0
- package/dist_ts/classes.trustedproxysecrets.js +5 -1
- package/dist_ts/functions.controllermanagementsurface.d.ts +4 -0
- package/dist_ts/functions.controllermanagementsurface.js +15 -1
- package/dist_ts/functions.gatewaycli.d.ts +24 -0
- package/dist_ts/functions.gatewaycli.js +395 -0
- package/dist_ts/functions.gatewayroute.d.ts +135 -0
- package/dist_ts/functions.gatewayroute.js +366 -0
- package/dist_ts/functions.inferencecli.js +30 -1
- package/dist_ts/functions.inferencecliarguments.d.ts +8 -2
- package/dist_ts/functions.inferencecliarguments.js +31 -3
- package/dist_ts/functions.proxycapacity.d.ts +50 -0
- package/dist_ts/functions.proxycapacity.js +142 -0
- package/dist_ts/functions.proxycapacitycli.d.ts +30 -0
- package/dist_ts/functions.proxycapacitycli.js +65 -0
- package/dist_ts/functions.remotecli.d.ts +30 -3
- package/dist_ts/functions.remotecli.js +44 -18
- package/dist_ts/interfaces.auth.d.ts +25 -4
- package/dist_ts/interfaces.auth.js +7 -1
- package/dist_ts/plugins.d.ts +2 -0
- package/dist_ts/plugins.js +4 -1
- package/dist_ts_authswitch/authority-placement.js +3 -17
- package/dist_ts_authswitch/authority-usagelimit.d.ts +29 -0
- package/dist_ts_authswitch/authority-usagelimit.js +66 -2
- package/dist_ts_authswitch/authority-usagewindows.d.ts +6 -0
- package/dist_ts_authswitch/authority-usagewindows.js +15 -1
- package/dist_ts_interfaces/gateway.d.ts +151 -0
- package/dist_ts_interfaces/gateway.js +66 -0
- package/dist_ts_interfaces/index.d.ts +2 -0
- package/dist_ts_interfaces/index.js +3 -1
- package/dist_ts_interfaces/management.d.ts +4 -4
- package/dist_ts_interfaces/management.js +3 -2
- package/dist_ts_interfaces/mcprequests.d.ts +14 -2
- package/dist_ts_interfaces/mcprequests.js +2 -1
- package/dist_ts_interfaces/proxycapacity.d.ts +99 -0
- package/dist_ts_interfaces/proxycapacity.js +74 -0
- package/package.json +4 -3
- package/readme.md +79 -5
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/aglapi/aglapisurface.document.ts +324 -0
- package/ts/aglapi/interfaces.ts +1 -0
- package/ts/classes.authmodels.ts +22 -3
- package/ts/classes.authstore.ts +15 -1
- package/ts/classes.cli.ts +7 -3
- package/ts/classes.controller.ts +134 -3
- package/ts/classes.controllermanagement.ts +40 -7
- package/ts/classes.gatewayclient.ts +401 -0
- package/ts/classes.gatewayclientstore.ts +272 -0
- package/ts/classes.inferencerouter.ts +12 -0
- package/ts/classes.inferenceservice.ts +27 -0
- package/ts/classes.mcpclient.ts +18 -0
- package/ts/classes.mcpcontrollerhost.ts +13 -0
- package/ts/classes.mcptools.ts +30 -2
- package/ts/classes.mcpvalidation.ts +5 -0
- package/ts/classes.proxycontrol.ts +16 -0
- package/ts/classes.proxycontrolclient.ts +30 -0
- package/ts/classes.proxydaemon.ts +8 -0
- package/ts/classes.proxymonitor.ts +12 -0
- package/ts/classes.trustedproxysecrets.ts +5 -0
- package/ts/functions.controllermanagementsurface.ts +15 -0
- package/ts/functions.gatewaycli.ts +436 -0
- package/ts/functions.gatewayroute.ts +429 -0
- package/ts/functions.inferencecli.ts +24 -0
- package/ts/functions.inferencecliarguments.ts +30 -4
- package/ts/functions.proxycapacity.ts +191 -0
- package/ts/functions.proxycapacitycli.ts +104 -0
- package/ts/functions.remotecli.ts +56 -20
- package/ts/interfaces.auth.ts +28 -4
- package/ts/plugins.ts +5 -0
- package/ts_authswitch/authority-placement.ts +2 -15
- package/ts_authswitch/authority-usagelimit.ts +84 -1
- package/ts_authswitch/authority-usagewindows.ts +13 -0
- package/ts_interfaces/gateway.ts +242 -0
- package/ts_interfaces/index.ts +2 -0
- package/ts_interfaces/management.ts +6 -4
- package/ts_interfaces/mcprequests.ts +18 -0
- package/ts_interfaces/proxycapacity.ts +162 -0
- package/ts_web/00_commitinfo_data.ts +1 -1
- package/ts_web/classes.browserpresentation.ts +13 -5
- package/ts_web/elements.accounts.ts +40 -113
- package/ts_web/elements.configurationpane.ts +24 -37
- package/ts_web/elements.devices.ts +4 -17
- package/ts_web/elements.flexlimitstrip.ts +21 -70
- package/ts_web/elements.harnesscontrollerapp.ts +91 -185
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import {
|
|
3
|
+
ControllerGatewayClientStore,
|
|
4
|
+
controllerGatewayEnrolment,
|
|
5
|
+
type IControllerGatewayClientDocument,
|
|
6
|
+
type IControllerGatewaySyncRecord,
|
|
7
|
+
} from './classes.gatewayclientstore.js';
|
|
8
|
+
import type { ControllerTrustedProxySecrets } from './classes.trustedproxysecrets.js';
|
|
9
|
+
import {
|
|
10
|
+
deleteGatewayRoutes,
|
|
11
|
+
gatewayContextProblem,
|
|
12
|
+
gatewayProblemOf,
|
|
13
|
+
gatewayRouteHeaderRefusal,
|
|
14
|
+
gatewayRouteReadBack,
|
|
15
|
+
gatewayRouteSyncOutcome,
|
|
16
|
+
gatewayRouteSyncRequest,
|
|
17
|
+
GatewayClientTransport,
|
|
18
|
+
GatewaySyncProblemError,
|
|
19
|
+
type IGatewayRouteSpec,
|
|
20
|
+
} from './functions.gatewayroute.js';
|
|
21
|
+
import type { IControllerRuntimeConfig } from './interfaces.config.js';
|
|
22
|
+
import {
|
|
23
|
+
controllerGatewayProblemKind,
|
|
24
|
+
type IControllerGatewayDns,
|
|
25
|
+
type IControllerGatewayProblem,
|
|
26
|
+
type IControllerGatewayStatus,
|
|
27
|
+
type TControllerGatewayState,
|
|
28
|
+
} from '../ts_interfaces/index.js';
|
|
29
|
+
|
|
30
|
+
type IReq_GetGatewayClientContext = plugins.servezoneInterfaces.requests.gateway.IReq_GetGatewayClientContext;
|
|
31
|
+
type IReq_GetGatewayClientRoutes = plugins.servezoneInterfaces.requests.gateway.IReq_GetGatewayClientRoutes;
|
|
32
|
+
type IReq_SyncGatewayClientRoute = plugins.servezoneInterfaces.requests.gateway.IReq_SyncGatewayClientRoute;
|
|
33
|
+
|
|
34
|
+
/** The timers a scheduler runs on: Node's own, or a test's clock. */
|
|
35
|
+
export interface IGatewaySyncClock {
|
|
36
|
+
now(): number;
|
|
37
|
+
setTimeout(callbackArg: () => void, delayMsArg: number): unknown;
|
|
38
|
+
clearTimeout(handleArg: unknown): void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const nodeClock: IGatewaySyncClock = {
|
|
42
|
+
now: () => Date.now(),
|
|
43
|
+
setTimeout: (callbackArg, delayMsArg) => setTimeout(callbackArg, delayMsArg),
|
|
44
|
+
clearTimeout: (handleArg) => clearTimeout(handleArg as NodeJS.Timeout),
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* When the gateway route is synced again (Linus, AGL-828): a failure a later sync can fix is retried with jittered
|
|
49
|
+
* exponential backoff from 30 s up to 15 min, reset by a sync that writes the route; a written route is synced again
|
|
50
|
+
* after six hours to repair drift; a gateway without request headers is asked again with the same backoff once, up to
|
|
51
|
+
* 15 min, and then at every six-hour sync; a terminal failure waits for the operator.
|
|
52
|
+
*/
|
|
53
|
+
export const gatewaySyncTimings = Object.freeze({
|
|
54
|
+
retryInitialMs: 30_000,
|
|
55
|
+
retryMaximumMs: 15 * 60_000,
|
|
56
|
+
/** ±20 % around the nominal delay, within the maximum. */
|
|
57
|
+
retryJitter: 0.2,
|
|
58
|
+
resyncMs: 6 * 60 * 60_000,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
/** The delay before retry `attemptArg` (1 for the first) after a transient failure. */
|
|
62
|
+
export const gatewayRetryDelayMs = (attemptArg: number, randomArg: () => number): number => {
|
|
63
|
+
const { retryInitialMs, retryMaximumMs, retryJitter } = gatewaySyncTimings;
|
|
64
|
+
const nominal = Math.min(retryInitialMs * 2 ** Math.min(Math.max(attemptArg, 1) - 1, 30), retryMaximumMs);
|
|
65
|
+
const factor = 1 - retryJitter + 2 * retryJitter * Math.min(Math.max(randomArg(), 0), 1);
|
|
66
|
+
return Math.min(Math.round(nominal * factor), retryMaximumMs);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** How a sync ended, for the scheduler: what it decides the next sync by. */
|
|
70
|
+
export type TGatewaySyncPassResult = 'synced' | 'transient' | 'waiting' | 'terminal' | 'idle';
|
|
71
|
+
|
|
72
|
+
/** The waits of a backoff from 30 s until one reaches 15 min: after them, a waiting state is asked every six hours. */
|
|
73
|
+
export const gatewayWaitingRetries = Math.ceil(Math.log2(gatewaySyncTimings.retryMaximumMs / gatewaySyncTimings.retryInitialMs)) + 1;
|
|
74
|
+
|
|
75
|
+
export interface IGatewaySyncSchedulerOptions {
|
|
76
|
+
pass: () => Promise<TGatewaySyncPassResult>;
|
|
77
|
+
clock?: IGatewaySyncClock;
|
|
78
|
+
random?: () => number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Runs one sync at a time: first at `start`, then as the last one's result decides (`gatewaySyncTimings`), and on
|
|
83
|
+
* demand (`syncNow`), which replaces the sync that was scheduled. `close` clears the timer and waits for a running
|
|
84
|
+
* sync; nothing runs after it.
|
|
85
|
+
*/
|
|
86
|
+
export class GatewaySyncScheduler {
|
|
87
|
+
private readonly clock: IGatewaySyncClock;
|
|
88
|
+
private readonly random: () => number;
|
|
89
|
+
private chain: Promise<void> = Promise.resolve();
|
|
90
|
+
private timer: unknown;
|
|
91
|
+
private timerDueAt: number | undefined;
|
|
92
|
+
private attempts = 0;
|
|
93
|
+
private waitingAttempts = 0;
|
|
94
|
+
private closed = false;
|
|
95
|
+
|
|
96
|
+
constructor(private readonly options: IGatewaySyncSchedulerOptions) {
|
|
97
|
+
this.clock = options.clock ?? nodeClock;
|
|
98
|
+
this.random = options.random ?? Math.random;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Schedules the first sync at once; it runs after the caller's turn, never inside it. */
|
|
102
|
+
public start(): void {
|
|
103
|
+
this.schedule(0);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Runs a sync now, after one that is running, and resolves once it ended. */
|
|
107
|
+
public syncNow(): Promise<void> {
|
|
108
|
+
if (this.closed) return Promise.reject(new Error('The gateway client is stopped.'));
|
|
109
|
+
this.cancelTimer();
|
|
110
|
+
return this.enqueue();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** When the next sync runs on its own; `undefined` while none is scheduled. */
|
|
114
|
+
public nextSyncAt(): number | undefined {
|
|
115
|
+
return this.timerDueAt;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Whether a timer is armed; false after `close`. */
|
|
119
|
+
public hasTimer(): boolean {
|
|
120
|
+
return this.timer !== undefined;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
public async close(): Promise<void> {
|
|
124
|
+
this.closed = true;
|
|
125
|
+
this.cancelTimer();
|
|
126
|
+
await this.chain;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private schedule(delayMsArg: number): void {
|
|
130
|
+
this.cancelTimer();
|
|
131
|
+
if (this.closed) return;
|
|
132
|
+
this.timerDueAt = this.clock.now() + delayMsArg;
|
|
133
|
+
this.timer = this.clock.setTimeout(() => {
|
|
134
|
+
this.timer = undefined;
|
|
135
|
+
this.timerDueAt = undefined;
|
|
136
|
+
void this.enqueue();
|
|
137
|
+
}, delayMsArg);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private cancelTimer(): void {
|
|
141
|
+
if (this.timer !== undefined) this.clock.clearTimeout(this.timer);
|
|
142
|
+
this.timer = undefined;
|
|
143
|
+
this.timerDueAt = undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private enqueue(): Promise<void> {
|
|
147
|
+
const run = this.chain.then(() => this.runOnce());
|
|
148
|
+
this.chain = run.catch(() => undefined);
|
|
149
|
+
return run;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private async runOnce(): Promise<void> {
|
|
153
|
+
if (this.closed) return;
|
|
154
|
+
// A sync now replaces the one that was scheduled.
|
|
155
|
+
this.cancelTimer();
|
|
156
|
+
let result: TGatewaySyncPassResult;
|
|
157
|
+
try {
|
|
158
|
+
result = await this.options.pass();
|
|
159
|
+
} catch {
|
|
160
|
+
result = 'transient';
|
|
161
|
+
}
|
|
162
|
+
if (this.closed) return;
|
|
163
|
+
if (result !== 'transient') this.attempts = 0;
|
|
164
|
+
if (result !== 'waiting') this.waitingAttempts = 0;
|
|
165
|
+
if (result === 'synced') {
|
|
166
|
+
this.schedule(gatewaySyncTimings.resyncMs);
|
|
167
|
+
} else if (result === 'transient') {
|
|
168
|
+
this.attempts += 1;
|
|
169
|
+
this.schedule(gatewayRetryDelayMs(this.attempts, this.random));
|
|
170
|
+
} else if (result === 'waiting') {
|
|
171
|
+
this.waitingAttempts += 1;
|
|
172
|
+
this.schedule(this.waitingAttempts <= gatewayWaitingRetries
|
|
173
|
+
? gatewayRetryDelayMs(this.waitingAttempts, this.random) : gatewaySyncTimings.resyncMs);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export interface IControllerGatewayClientOptions {
|
|
179
|
+
store: ControllerGatewayClientStore;
|
|
180
|
+
/** The controller's runtime configuration: its origin, port and TLS mode. */
|
|
181
|
+
runtimeConfig: () => IControllerRuntimeConfig;
|
|
182
|
+
/** The trusted-proxy secret the route carries; absent in local mode. */
|
|
183
|
+
secrets: () => ControllerTrustedProxySecrets | undefined;
|
|
184
|
+
clock?: IGatewaySyncClock;
|
|
185
|
+
random?: () => number;
|
|
186
|
+
/** Per gateway request. */
|
|
187
|
+
requestTimeoutMs?: number;
|
|
188
|
+
/** Where a change of the client's state is reported; the controller's log by default. */
|
|
189
|
+
log?: (textArg: string) => void;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The controller's gateway client (AGL-828): with the credential `agl remote gateway enrol` stored, it keeps the
|
|
194
|
+
* controller's route on its gateway, in the background, after the listener is up; the controller's start never waits
|
|
195
|
+
* for the gateway. A sync checks the credential, deletes the client's routes the controller no longer serves (an
|
|
196
|
+
* earlier hostname), and writes the route with the trusted-proxy secret, then confirms a rotation the route carries.
|
|
197
|
+
*/
|
|
198
|
+
export class ControllerGatewayClient {
|
|
199
|
+
private readonly scheduler: GatewaySyncScheduler;
|
|
200
|
+
private readonly abortController = new AbortController();
|
|
201
|
+
private readonly log: (textArg: string) => void;
|
|
202
|
+
private state: TControllerGatewayState = 'not_enrolled';
|
|
203
|
+
private record: IControllerGatewayClientDocument | undefined;
|
|
204
|
+
private lastSync: IControllerGatewaySyncRecord = {};
|
|
205
|
+
private loggedProblem: string | undefined;
|
|
206
|
+
|
|
207
|
+
constructor(private readonly options: IControllerGatewayClientOptions) {
|
|
208
|
+
this.log = options.log ?? ((textArg) => { console.log(textArg); });
|
|
209
|
+
this.scheduler = new GatewaySyncScheduler({
|
|
210
|
+
pass: () => this.pass(),
|
|
211
|
+
...(options.clock ? { clock: options.clock } : {}),
|
|
212
|
+
...(options.random ? { random: options.random } : {}),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Reads the enrolment, for the status to report before the first sync. */
|
|
217
|
+
public async load(): Promise<void> {
|
|
218
|
+
this.adopt(await this.options.store.read());
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Schedules the first sync; it runs in the background. */
|
|
222
|
+
public start(): void {
|
|
223
|
+
if (this.record?.active && !this.record.candidate) this.state = 'syncing';
|
|
224
|
+
this.scheduler.start();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
public status(): IControllerGatewayStatus {
|
|
228
|
+
const record = this.record;
|
|
229
|
+
const credential = record?.active ?? record?.candidate;
|
|
230
|
+
const nextSyncAt = this.scheduler.nextSyncAt();
|
|
231
|
+
const secrets = this.options.secrets();
|
|
232
|
+
return {
|
|
233
|
+
state: this.state,
|
|
234
|
+
...(credential ? { enrolment: controllerGatewayEnrolment(credential, this.options.runtimeConfig().controllerPort) } : {}),
|
|
235
|
+
...(this.lastSync.syncedAt === undefined ? {} : { lastSyncedAt: this.lastSync.syncedAt }),
|
|
236
|
+
...(this.lastSync.dns ? { dns: { ...this.lastSync.dns } } : {}),
|
|
237
|
+
...(this.lastSync.sourceProfileVerified === undefined ? {} : { sourceProfileVerified: this.lastSync.sourceProfileVerified }),
|
|
238
|
+
...(this.lastSync.problem ? { problem: { ...this.lastSync.problem } } : {}),
|
|
239
|
+
...(nextSyncAt === undefined ? {} : { nextSyncAt }),
|
|
240
|
+
...(secrets?.rotating() ? { rotationPending: true } : {}),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Syncs now (`agl remote gateway sync`), after rotating the trusted-proxy secret when `rotate` is set: the route
|
|
246
|
+
* then carries the new secret, and the previous one is refused once a sync wrote it. Resolves with the status after
|
|
247
|
+
* that sync.
|
|
248
|
+
*/
|
|
249
|
+
public async sync(optionsArg: { rotate: boolean }): Promise<IControllerGatewayStatus> {
|
|
250
|
+
if (optionsArg.rotate) {
|
|
251
|
+
const record = await this.options.store.read();
|
|
252
|
+
if (!record?.active) throw new Error('This controller is not enrolled with a gateway, so no route carries a rotated secret.');
|
|
253
|
+
const secrets = this.options.secrets();
|
|
254
|
+
if (!secrets) throw new Error('This controller runs no trusted reverse proxy, so it has no secret to rotate.');
|
|
255
|
+
await secrets.rotate();
|
|
256
|
+
}
|
|
257
|
+
await this.scheduler.syncNow();
|
|
258
|
+
return this.status();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Whether any timer is armed; false once closed. */
|
|
262
|
+
public hasTimer(): boolean {
|
|
263
|
+
return this.scheduler.hasTimer();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Stops every timer, aborts a running sync's requests and waits for it. */
|
|
267
|
+
public async close(): Promise<void> {
|
|
268
|
+
this.abortController.abort(new Error('The controller is stopping.'));
|
|
269
|
+
await this.scheduler.close();
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private adopt(recordArg: IControllerGatewayClientDocument | undefined): void {
|
|
273
|
+
this.record = recordArg;
|
|
274
|
+
this.lastSync = structuredClone(recordArg?.lastSync ?? {});
|
|
275
|
+
if (!recordArg) this.state = 'not_enrolled';
|
|
276
|
+
else if (recordArg.candidate) this.state = 'finalize_pending';
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private async pass(): Promise<TGatewaySyncPassResult> {
|
|
280
|
+
let record: IControllerGatewayClientDocument | undefined;
|
|
281
|
+
try {
|
|
282
|
+
record = await this.options.store.read();
|
|
283
|
+
} catch (errorArg) {
|
|
284
|
+
this.log(`The gateway client could not read its enrolment: ${errorArg instanceof Error ? errorArg.message : String(errorArg)}`);
|
|
285
|
+
return 'transient';
|
|
286
|
+
}
|
|
287
|
+
this.adopt(record);
|
|
288
|
+
const active = record?.active;
|
|
289
|
+
if (!record || !active) {
|
|
290
|
+
if (record?.candidate) {
|
|
291
|
+
return this.finish(undefined, { code: 'finalize_pending', message: 'The gateway has not confirmed the enrolment\'s '
|
|
292
|
+
+ 'credential. Stop the controller and run `agl remote gateway enrol` again to finish it.' });
|
|
293
|
+
}
|
|
294
|
+
return 'idle';
|
|
295
|
+
}
|
|
296
|
+
if (record.candidate) {
|
|
297
|
+
return this.finish(active.tokenId, { code: 'finalize_pending', message: 'A new enrolment is not finished. Stop the '
|
|
298
|
+
+ 'controller and run `agl remote gateway enrol` again to finish it.' });
|
|
299
|
+
}
|
|
300
|
+
const config = this.options.runtimeConfig();
|
|
301
|
+
if (config.tlsMode !== 'proxy') {
|
|
302
|
+
return this.finish(active.tokenId, { code: 'not_proxied', message: 'The controller is not behind a TLS reverse '
|
|
303
|
+
+ 'proxy (`agl remote set`), so it has no route.' });
|
|
304
|
+
}
|
|
305
|
+
this.state = 'syncing';
|
|
306
|
+
try {
|
|
307
|
+
// Refuses a stored URL that is plain http off loopback (`gateway_url_insecure`) before the token is unsealed.
|
|
308
|
+
const transport = new GatewayClientTransport(active.gatewayUrl, {
|
|
309
|
+
...(this.options.requestTimeoutMs === undefined ? {} : { timeoutMs: this.options.requestTimeoutMs }),
|
|
310
|
+
signal: this.abortController.signal,
|
|
311
|
+
});
|
|
312
|
+
const token = await this.options.store.unseal(active);
|
|
313
|
+
const context = await transport.fire<IReq_GetGatewayClientContext>('getGatewayClientContext', { apiToken: token });
|
|
314
|
+
const contextProblem = gatewayContextProblem(context, active.gatewayClientId);
|
|
315
|
+
if (contextProblem) throw new GatewaySyncProblemError(contextProblem);
|
|
316
|
+
// The client's routes for anything the controller no longer serves go first: an earlier hostname's. `agl remote
|
|
317
|
+
// set` refuses another hostname while enrolled, so this and `origin_changed` are the safety net for a leftover
|
|
318
|
+
// (an interrupted change, or a move an earlier release made after a rollback).
|
|
319
|
+
const hostname = new URL(config.publicOrigin).hostname;
|
|
320
|
+
const removed = await deleteGatewayRoutes(transport, token, (routeArg) => routeArg.ownership.appId === active.appId
|
|
321
|
+
&& routeArg.ownership.hostname === hostname && routeArg.ownership.routeRef === undefined);
|
|
322
|
+
if (removed.length > 0) this.log(`The gateway client deleted routes the controller no longer serves: ${removed.join(', ')}.`);
|
|
323
|
+
if (hostname !== active.hostname) {
|
|
324
|
+
throw new GatewaySyncProblemError({ code: 'origin_changed', message: `The controller's public origin is `
|
|
325
|
+
+ `${config.publicOrigin}, but it was enrolled for ${active.hostname}. Run \`agl remote gateway enrol\` again `
|
|
326
|
+
+ `for ${hostname}.` });
|
|
327
|
+
}
|
|
328
|
+
// No route is written without the trusted-proxy secret, which only a gateway that takes request headers sets.
|
|
329
|
+
const headerRefusal = gatewayRouteHeaderRefusal(context.capabilities);
|
|
330
|
+
if (headerRefusal) throw new GatewaySyncProblemError(headerRefusal);
|
|
331
|
+
const secrets = this.options.secrets();
|
|
332
|
+
if (!secrets) {
|
|
333
|
+
throw new GatewaySyncProblemError({ code: 'not_proxied', message: 'The controller has no trusted-proxy secret for its route.' });
|
|
334
|
+
}
|
|
335
|
+
const spec: IGatewayRouteSpec = {
|
|
336
|
+
gatewayClientId: active.gatewayClientId,
|
|
337
|
+
appId: active.appId,
|
|
338
|
+
hostname,
|
|
339
|
+
targetHost: active.targetHost,
|
|
340
|
+
targetPort: config.controllerPort,
|
|
341
|
+
};
|
|
342
|
+
// The secret the route carries: a rotation's while one is in progress, so the sync that writes it confirms it.
|
|
343
|
+
const carried = secrets.routeSecret();
|
|
344
|
+
const outcome = gatewayRouteSyncOutcome(await transport.fire<IReq_SyncGatewayClientRoute>(
|
|
345
|
+
'syncGatewayClientRoute',
|
|
346
|
+
gatewayRouteSyncRequest(token, spec, carried.secret),
|
|
347
|
+
));
|
|
348
|
+
if (!outcome.synced) throw new GatewaySyncProblemError(outcome.problem);
|
|
349
|
+
const readBack = gatewayRouteReadBack(
|
|
350
|
+
(await transport.fire<IReq_GetGatewayClientRoutes>('getGatewayClientRoutes', { apiToken: token })).routes,
|
|
351
|
+
spec,
|
|
352
|
+
);
|
|
353
|
+
if (readBack.problem) throw new GatewaySyncProblemError(readBack.problem);
|
|
354
|
+
// The route carries the secret: a rotation it carries ends, and the previous secret is refused from now on. One
|
|
355
|
+
// that began while this sync ran is carried by the next sync, which runs right after it.
|
|
356
|
+
if (secrets.routeSecret().generation === carried.generation) await secrets.confirm(carried.generation);
|
|
357
|
+
return await this.finish(active.tokenId, undefined, outcome.dns, readBack.sourceProfileVerified);
|
|
358
|
+
} catch (errorArg) {
|
|
359
|
+
if (this.abortController.signal.aborted) return 'idle';
|
|
360
|
+
return this.finish(active.tokenId, gatewayProblemOf(errorArg));
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Records a sync's end, in memory and in the database, and tells the scheduler what follows. */
|
|
365
|
+
private async finish(
|
|
366
|
+
tokenIdArg: string | undefined,
|
|
367
|
+
problemArg: IControllerGatewayProblem | undefined,
|
|
368
|
+
dnsArg?: IControllerGatewayDns,
|
|
369
|
+
sourceProfileVerifiedArg?: boolean,
|
|
370
|
+
): Promise<TGatewaySyncPassResult> {
|
|
371
|
+
const kind = problemArg === undefined ? undefined : controllerGatewayProblemKind[problemArg.code];
|
|
372
|
+
const transient = kind === 'transient';
|
|
373
|
+
const previous = this.lastSync;
|
|
374
|
+
const lastSync: IControllerGatewaySyncRecord = problemArg
|
|
375
|
+
? { ...(previous.syncedAt === undefined ? {} : { syncedAt: previous.syncedAt }),
|
|
376
|
+
...(previous.dns ? { dns: previous.dns } : {}),
|
|
377
|
+
...(previous.sourceProfileVerified === undefined ? {} : { sourceProfileVerified: previous.sourceProfileVerified }),
|
|
378
|
+
problem: problemArg }
|
|
379
|
+
: { syncedAt: this.options.clock?.now() ?? Date.now(), ...(dnsArg ? { dns: dnsArg } : {}),
|
|
380
|
+
...(sourceProfileVerifiedArg === undefined ? {} : { sourceProfileVerified: sourceProfileVerifiedArg }) };
|
|
381
|
+
const logged = problemArg ? `${problemArg.code}: ${problemArg.message}` : undefined;
|
|
382
|
+
if (logged !== this.loggedProblem) {
|
|
383
|
+
this.log(problemArg ? `The gateway route was not synced (${problemArg.code}${kind === 'terminal' ? '' : ', asked again'}): `
|
|
384
|
+
+ `${problemArg.message}` : 'The gateway route is synced.');
|
|
385
|
+
this.loggedProblem = logged;
|
|
386
|
+
}
|
|
387
|
+
if (tokenIdArg !== undefined) {
|
|
388
|
+
try {
|
|
389
|
+
await this.options.store.recordSync(tokenIdArg, lastSync);
|
|
390
|
+
} catch (errorArg) {
|
|
391
|
+
this.log(`The gateway client could not record its sync: ${errorArg instanceof Error ? errorArg.message : String(errorArg)}`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
// The status shows the sync's end once it is recorded; the scheduler arms the next one right after.
|
|
395
|
+
this.lastSync = lastSync;
|
|
396
|
+
this.state = !problemArg ? 'synced'
|
|
397
|
+
: problemArg.code === 'finalize_pending' ? 'finalize_pending'
|
|
398
|
+
: transient ? 'retrying' : kind === 'waiting' ? 'waiting' : 'failed';
|
|
399
|
+
return !problemArg ? 'synced' : kind === 'terminal' ? 'terminal' : kind === 'waiting' ? 'waiting' : 'transient';
|
|
400
|
+
}
|
|
401
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import type { ITpmSecretCodec } from './classes.tpmsecretcodec.js';
|
|
3
|
+
import {
|
|
4
|
+
controllerGatewayProblemCodes,
|
|
5
|
+
type IControllerGatewayDns,
|
|
6
|
+
type IControllerGatewayEnrolment,
|
|
7
|
+
type IControllerGatewayProblem,
|
|
8
|
+
type TControllerGatewayProblemCode,
|
|
9
|
+
} from '../ts_interfaces/index.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One gateway-client credential of a controller with everything it was issued for: the gateway, the client, the
|
|
13
|
+
* route it may write and the token, TPM2-sealed (`TpmSecretCodec`) under a name bound to the controller and the
|
|
14
|
+
* token id. The token's plaintext exists only in the process that uses it, never in a log, a file or the output.
|
|
15
|
+
*/
|
|
16
|
+
export interface IControllerGatewayCredential {
|
|
17
|
+
/** The gateway's API base URL; requests go to `<gatewayUrl>/typedrequest`. */
|
|
18
|
+
gatewayUrl: string;
|
|
19
|
+
/** `agl-<installation>-<port>`, type `custom`. */
|
|
20
|
+
gatewayClientId: string;
|
|
21
|
+
/** `controller-<port>`. */
|
|
22
|
+
appId: string;
|
|
23
|
+
hostname: string;
|
|
24
|
+
targetHost: string;
|
|
25
|
+
/** The gateway's id of the token; the seal name binds it. */
|
|
26
|
+
tokenId: string;
|
|
27
|
+
ciphertext: string;
|
|
28
|
+
/** Unix epoch milliseconds: when the gateway issued it (a candidate) or confirmed it (the active credential). */
|
|
29
|
+
at: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What the last sync of a running controller left for `agl remote gateway status` to show while it is stopped. */
|
|
33
|
+
export interface IControllerGatewaySyncRecord {
|
|
34
|
+
/** Unix epoch milliseconds of the last sync that wrote the route. */
|
|
35
|
+
syncedAt?: number;
|
|
36
|
+
dns?: IControllerGatewayDns;
|
|
37
|
+
/** Whether the gateway named the route's source profile as `LOCAL NETWORK` after that sync; false when it named none. */
|
|
38
|
+
sourceProfileVerified?: boolean;
|
|
39
|
+
/** Why the last sync failed; absent when it wrote the route. */
|
|
40
|
+
problem?: IControllerGatewayProblem;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface IControllerGatewayClientDocument {
|
|
44
|
+
/** `controller:<port>`. */
|
|
45
|
+
id: string;
|
|
46
|
+
/** The credential the controller syncs with, once the gateway confirmed it (`finalizeGatewayClientCredential`). */
|
|
47
|
+
active?: IControllerGatewayCredential;
|
|
48
|
+
/**
|
|
49
|
+
* A credential the gateway issued that is not confirmed yet: sealed and stored before the confirmation is asked for,
|
|
50
|
+
* so a confirmation whose answer is lost is asked for again with the same credential.
|
|
51
|
+
*/
|
|
52
|
+
candidate?: IControllerGatewayCredential;
|
|
53
|
+
lastSync?: IControllerGatewaySyncRecord;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const isText = (valueArg: unknown, maximumArg: number): valueArg is string => (
|
|
57
|
+
typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= maximumArg
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
const isRecordOf = (valueArg: unknown, requiredArg: readonly string[], optionalArg: readonly string[] = []): valueArg is Record<string, unknown> => (
|
|
61
|
+
!!valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg)
|
|
62
|
+
&& requiredArg.every((keyArg) => Object.hasOwn(valueArg, keyArg))
|
|
63
|
+
&& Object.keys(valueArg).every((keyArg) => requiredArg.includes(keyArg) || optionalArg.includes(keyArg))
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
const isTime = (valueArg: unknown): valueArg is number => Number.isSafeInteger(valueArg) && (valueArg as number) >= 0;
|
|
67
|
+
|
|
68
|
+
/** A gateway token id as it may appear in a seal name. */
|
|
69
|
+
const gatewayTokenIdPattern = /^[A-Za-z0-9_.-]{1,64}$/u;
|
|
70
|
+
|
|
71
|
+
const isCredential = (valueArg: unknown): valueArg is IControllerGatewayCredential => (
|
|
72
|
+
isRecordOf(valueArg, ['gatewayUrl', 'gatewayClientId', 'appId', 'hostname', 'targetHost', 'tokenId', 'ciphertext', 'at'])
|
|
73
|
+
&& isText(valueArg.gatewayUrl, 2048) && isText(valueArg.gatewayClientId, 128) && isText(valueArg.appId, 128)
|
|
74
|
+
&& isText(valueArg.hostname, 253) && isText(valueArg.targetHost, 253)
|
|
75
|
+
&& typeof valueArg.tokenId === 'string' && gatewayTokenIdPattern.test(valueArg.tokenId)
|
|
76
|
+
&& typeof valueArg.ciphertext === 'string' && /^[A-Za-z0-9_-]{1,131072}$/u.test(valueArg.ciphertext)
|
|
77
|
+
&& isTime(valueArg.at)
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
const isSyncRecord = (valueArg: unknown): valueArg is IControllerGatewaySyncRecord => {
|
|
81
|
+
if (!isRecordOf(valueArg, [], ['syncedAt', 'dns', 'sourceProfileVerified', 'problem'])) return false;
|
|
82
|
+
const { syncedAt, dns, sourceProfileVerified, problem } = valueArg;
|
|
83
|
+
return (syncedAt === undefined || isTime(syncedAt))
|
|
84
|
+
&& (sourceProfileVerified === undefined || typeof sourceProfileVerified === 'boolean')
|
|
85
|
+
&& (dns === undefined || (isRecordOf(dns, ['status', 'owned']) && isText(dns.status, 64) && typeof dns.owned === 'boolean'))
|
|
86
|
+
&& (problem === undefined || (isRecordOf(problem, ['code', 'message'])
|
|
87
|
+
&& controllerGatewayProblemCodes.includes(problem.code as TControllerGatewayProblemCode)
|
|
88
|
+
&& isText(problem.message, 4096)));
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const assertDocument: (valueArg: unknown) => asserts valueArg is IControllerGatewayClientDocument = (valueArg) => {
|
|
92
|
+
if (!isRecordOf(valueArg, ['id'], ['active', 'candidate', 'lastSync'])
|
|
93
|
+
|| typeof valueArg.id !== 'string' || !/^controller:[1-9][0-9]{0,4}$/u.test(valueArg.id)
|
|
94
|
+
|| (valueArg.active === undefined && valueArg.candidate === undefined)
|
|
95
|
+
|| (valueArg.active !== undefined && !isCredential(valueArg.active))
|
|
96
|
+
|| (valueArg.candidate !== undefined && !isCredential(valueArg.candidate))
|
|
97
|
+
|| (valueArg.lastSync !== undefined && !isSyncRecord(valueArg.lastSync))) {
|
|
98
|
+
throw new Error('Invalid gateway client record.');
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
@plugins.nosqldb.managed({ collectionName: 'agl_controller_gateway_clients' })
|
|
103
|
+
@plugins.nosqldb.exactPersistence({ assertDocument })
|
|
104
|
+
export class ControllerGatewayClientModel
|
|
105
|
+
extends plugins.nosqldb.SmartDataDbDoc<ControllerGatewayClientModel, IControllerGatewayClientDocument> {
|
|
106
|
+
declare static exact: plugins.nosqldb.TExact<ControllerGatewayClientModel>;
|
|
107
|
+
@plugins.nosqldb.unI() public id!: string;
|
|
108
|
+
@plugins.nosqldb.svDb() public active?: IControllerGatewayCredential;
|
|
109
|
+
@plugins.nosqldb.svDb() public candidate?: IControllerGatewayCredential;
|
|
110
|
+
@plugins.nosqldb.svDb() public lastSync?: IControllerGatewaySyncRecord;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const readStored = (controllerIdArg: string) => ControllerGatewayClientModel.exact.findStoredOne({ id: controllerIdArg });
|
|
114
|
+
|
|
115
|
+
type TStoredRecord = NonNullable<Awaited<ReturnType<typeof readStored>>>;
|
|
116
|
+
|
|
117
|
+
export interface IControllerGatewayClientStoreOptions {
|
|
118
|
+
/** `controller:<port>`. */
|
|
119
|
+
controllerId: string;
|
|
120
|
+
/** The controller database's issuer id: a credential is sealed under a name bound to it. */
|
|
121
|
+
issuerId: string;
|
|
122
|
+
codec: ITpmSecretCodec;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The fields of a credential that say what it was issued for, without the token. */
|
|
126
|
+
export type TControllerGatewayCredentialSpec = Pick<IControllerGatewayCredential,
|
|
127
|
+
'gatewayUrl' | 'gatewayClientId' | 'appId' | 'hostname' | 'targetHost'>;
|
|
128
|
+
|
|
129
|
+
/** What `agl remote gateway status` and the management status report of an enrolment, without its token. */
|
|
130
|
+
export const controllerGatewayEnrolment = (
|
|
131
|
+
credentialArg: IControllerGatewayCredential,
|
|
132
|
+
portArg: number,
|
|
133
|
+
): IControllerGatewayEnrolment => ({
|
|
134
|
+
gatewayUrl: credentialArg.gatewayUrl,
|
|
135
|
+
gatewayClientId: credentialArg.gatewayClientId,
|
|
136
|
+
appId: credentialArg.appId,
|
|
137
|
+
hostname: credentialArg.hostname,
|
|
138
|
+
target: { host: credentialArg.targetHost, port: portArg },
|
|
139
|
+
enrolledAt: credentialArg.at,
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A controller's gateway-client record in its database (`agl_controller_gateway_clients`): the active credential, a
|
|
144
|
+
* candidate awaiting the gateway's confirmation, and what the last sync left. Only `agl remote gateway` writes the
|
|
145
|
+
* credentials, against a stopped controller; the running controller writes only `lastSync`.
|
|
146
|
+
*/
|
|
147
|
+
export class ControllerGatewayClientStore {
|
|
148
|
+
constructor(private readonly options: IControllerGatewayClientStoreOptions) {}
|
|
149
|
+
|
|
150
|
+
public get controllerId(): string {
|
|
151
|
+
return this.options.controllerId;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
public async read(): Promise<IControllerGatewayClientDocument | undefined> {
|
|
155
|
+
const stored = await readStored(this.options.controllerId);
|
|
156
|
+
return stored ? ControllerGatewayClientModel.exact.toPersisted(stored) : undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The token of `credentialArg`, unsealed; the caller wipes nothing, the string is the gateway's own text. */
|
|
160
|
+
public async unseal(credentialArg: IControllerGatewayCredential): Promise<string> {
|
|
161
|
+
let bytes: Uint8Array;
|
|
162
|
+
try {
|
|
163
|
+
bytes = await this.options.codec.unseal(this.sealName(credentialArg.tokenId), credentialArg.ciphertext);
|
|
164
|
+
} catch (errorArg) {
|
|
165
|
+
throw new Error(`The gateway credential of ${this.options.controllerId} cannot be unsealed on this machine. `
|
|
166
|
+
+ 'Enrol again with `agl remote gateway enrol`.', { cause: errorArg });
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
return Buffer.from(bytes).toString('utf8');
|
|
170
|
+
} finally {
|
|
171
|
+
bytes.fill(0);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Seals a credential the gateway just issued and stores it as the candidate, before its confirmation is asked
|
|
177
|
+
* for. A candidate stored before is replaced: the gateway superseded it by issuing this one.
|
|
178
|
+
*/
|
|
179
|
+
public async storeCandidate(specArg: TControllerGatewayCredentialSpec, tokenIdArg: string, tokenArg: string): Promise<IControllerGatewayCredential> {
|
|
180
|
+
if (!gatewayTokenIdPattern.test(tokenIdArg)) throw new Error('The gateway issued a credential with an invalid id.');
|
|
181
|
+
const bytes = Buffer.from(tokenArg, 'utf8');
|
|
182
|
+
let ciphertext: string;
|
|
183
|
+
try {
|
|
184
|
+
ciphertext = await this.options.codec.seal(this.sealName(tokenIdArg), bytes);
|
|
185
|
+
} finally {
|
|
186
|
+
bytes.fill(0);
|
|
187
|
+
}
|
|
188
|
+
const candidate: IControllerGatewayCredential = { ...specArg, tokenId: tokenIdArg, ciphertext, at: Date.now() };
|
|
189
|
+
const stored = await readStored(this.options.controllerId);
|
|
190
|
+
if (!stored) {
|
|
191
|
+
const inserted = await ControllerGatewayClientModel.exact.insert({ id: this.options.controllerId, candidate });
|
|
192
|
+
if (inserted.status !== 'inserted') throw new Error('The gateway client record changed concurrently.');
|
|
193
|
+
return candidate;
|
|
194
|
+
}
|
|
195
|
+
await this.transition(stored, (modelArg) => { modelArg.candidate = candidate; });
|
|
196
|
+
return candidate;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Makes the confirmed candidate `tokenIdArg` the active credential; the previous one is gone from the gateway. */
|
|
200
|
+
public async promoteCandidate(tokenIdArg: string): Promise<IControllerGatewayCredential> {
|
|
201
|
+
const stored = await this.requireStored();
|
|
202
|
+
const record = ControllerGatewayClientModel.exact.toPersisted(stored);
|
|
203
|
+
if (record.candidate?.tokenId !== tokenIdArg) throw new Error('The gateway client record changed concurrently.');
|
|
204
|
+
const active: IControllerGatewayCredential = { ...record.candidate, at: Date.now() };
|
|
205
|
+
await this.transition(stored, (modelArg) => {
|
|
206
|
+
modelArg.active = active;
|
|
207
|
+
delete modelArg.candidate;
|
|
208
|
+
// A new credential starts without the previous one's outcome.
|
|
209
|
+
delete modelArg.lastSync;
|
|
210
|
+
});
|
|
211
|
+
return active;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Drops a candidate the gateway refuses to confirm; the record goes when it holds nothing else. */
|
|
215
|
+
public async dropCandidate(tokenIdArg: string): Promise<void> {
|
|
216
|
+
const stored = await this.requireStored();
|
|
217
|
+
const record = ControllerGatewayClientModel.exact.toPersisted(stored);
|
|
218
|
+
if (record.candidate?.tokenId !== tokenIdArg) throw new Error('The gateway client record changed concurrently.');
|
|
219
|
+
if (!record.active) {
|
|
220
|
+
await this.forget();
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
await this.transition(stored, (modelArg) => { delete modelArg.candidate; });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Records what a sync of the running controller found; the record must still hold `tokenIdArg` as active. */
|
|
227
|
+
public async recordSync(tokenIdArg: string, syncArg: IControllerGatewaySyncRecord): Promise<void> {
|
|
228
|
+
const stored = await this.requireStored();
|
|
229
|
+
if (ControllerGatewayClientModel.exact.toPersisted(stored).active?.tokenId !== tokenIdArg) {
|
|
230
|
+
throw new Error('The gateway client record changed outside this controller.');
|
|
231
|
+
}
|
|
232
|
+
await this.transition(stored, (modelArg) => { modelArg.lastSync = structuredClone(syncArg); });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Removes the record; whether there was one. */
|
|
236
|
+
public async forget(): Promise<boolean> {
|
|
237
|
+
const stored = await readStored(this.options.controllerId);
|
|
238
|
+
if (!stored) return false;
|
|
239
|
+
const deleted = await ControllerGatewayClientModel.exact.delete({ current: stored });
|
|
240
|
+
if (deleted.status !== 'deleted' && await readStored(this.options.controllerId)) {
|
|
241
|
+
throw new Error('The gateway client record could not be removed.');
|
|
242
|
+
}
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private sealName(tokenIdArg: string): string {
|
|
247
|
+
return `agl-controller.${this.options.issuerId.slice(0, 22)}.${this.options.controllerId.replace(':', '-')}.gateway.${tokenIdArg}`;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private async requireStored(): Promise<TStoredRecord> {
|
|
251
|
+
const stored = await readStored(this.options.controllerId);
|
|
252
|
+
if (!stored) throw new Error(`${this.options.controllerId} is not enrolled with a gateway.`);
|
|
253
|
+
return stored;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private async transition(storedArg: TStoredRecord, changeArg: (modelArg: ControllerGatewayClientModel) => void): Promise<void> {
|
|
257
|
+
const result = await ControllerGatewayClientModel.exact.transition({ current: storedArg, change: changeArg });
|
|
258
|
+
if (result.status !== 'transitioned') throw new Error('The gateway client record changed concurrently.');
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* The hostnames the gateway enrolment of `controllerIdArg` holds a route for, finished or not (its active and its
|
|
264
|
+
* candidate credential's); empty when it has none.
|
|
265
|
+
*/
|
|
266
|
+
export const controllerGatewayEnrolledHostnames = async (controllerIdArg: string): Promise<string[]> => {
|
|
267
|
+
const stored = await readStored(controllerIdArg);
|
|
268
|
+
if (!stored) return [];
|
|
269
|
+
const record = ControllerGatewayClientModel.exact.toPersisted(stored);
|
|
270
|
+
return [...new Set([record.active?.hostname, record.candidate?.hostname]
|
|
271
|
+
.filter((hostnameArg): hostnameArg is string => hostnameArg !== undefined))];
|
|
272
|
+
};
|