agl 41.2.0 → 42.1.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 +41 -0
- package/dist_serve/bundle.js +2625 -2278
- package/dist_serve/bundle.js.map +2 -2
- package/dist_serve/bundle.js.third-party-notices.json +3 -68
- package/dist_serve/bundle.js.third-party-notices.txt +4 -137
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/aglapi/aglapisurface.document.js +4 -4
- package/dist_ts/classes.authmodels.d.ts +2 -8
- package/dist_ts/classes.authmodels.js +60 -23
- package/dist_ts/classes.authstore.d.ts +24 -0
- package/dist_ts/classes.authstore.js +185 -23
- package/dist_ts/classes.cli.d.ts +3 -6
- package/dist_ts/classes.cli.js +38 -51
- package/dist_ts/classes.config.d.ts +17 -3
- package/dist_ts/classes.config.js +55 -18
- package/dist_ts/classes.controller.d.ts +83 -14
- package/dist_ts/classes.controller.js +545 -229
- package/dist_ts/classes.controllerdevices.d.ts +128 -0
- package/dist_ts/classes.controllerdevices.js +472 -0
- package/dist_ts/classes.controllermanagement.d.ts +42 -9
- package/dist_ts/classes.controllermanagement.js +72 -23
- package/dist_ts/classes.controllerservice.d.ts +3 -31
- package/dist_ts/classes.controllerservice.js +3 -47
- package/dist_ts/classes.mcpcontrollerhost.js +9 -3
- package/dist_ts/classes.processinspection.d.ts +8 -1
- package/dist_ts/classes.processinspection.js +92 -2
- package/dist_ts/classes.proxycontrol.js +6 -1
- package/dist_ts/classes.proxydaemon.d.ts +2 -2
- package/dist_ts/classes.proxydaemon.js +1 -1
- package/dist_ts/classes.proxystore.d.ts +2 -11
- package/dist_ts/classes.proxystore.js +3 -25
- package/dist_ts/classes.sessionfeed.d.ts +10 -1
- package/dist_ts/classes.sessionfeed.js +12 -2
- package/dist_ts/classes.tpmsecretcodec.d.ts +13 -0
- package/dist_ts/classes.tpmsecretcodec.js +28 -0
- package/dist_ts/classes.trustedproxysecrets.d.ts +91 -0
- package/dist_ts/classes.trustedproxysecrets.js +338 -0
- package/dist_ts/classes.upgradecoordinator.d.ts +14 -1
- package/dist_ts/classes.upgradecoordinator.js +21 -3
- package/dist_ts/classes.upgradetransaction.d.ts +32 -0
- package/dist_ts/classes.upgradetransaction.js +101 -4
- package/dist_ts/classes.validation.d.ts +2 -0
- package/dist_ts/classes.validation.js +2 -2
- package/dist_ts/functions.controlleradmission.d.ts +67 -0
- package/dist_ts/functions.controlleradmission.js +127 -0
- package/dist_ts/functions.deviceapi.d.ts +28 -0
- package/dist_ts/functions.deviceapi.js +246 -0
- package/dist_ts/functions.deviceproof.d.ts +33 -0
- package/dist_ts/functions.deviceproof.js +93 -0
- package/dist_ts/functions.remotecli.d.ts +27 -0
- package/dist_ts/functions.remotecli.js +241 -0
- package/dist_ts/functions.retiredenvironment.d.ts +11 -2
- package/dist_ts/functions.retiredenvironment.js +22 -5
- package/dist_ts/index.d.ts +1 -0
- package/dist_ts/index.js +2 -1
- package/dist_ts/interfaces.auth.d.ts +29 -4
- package/dist_ts/interfaces.auth.js +10 -1
- package/dist_ts/interfaces.config.d.ts +14 -0
- package/dist_ts/interfaces.config.js +9 -2
- package/dist_ts/interfaces.lifecycle.d.ts +3 -0
- package/dist_ts_authswitch/classes.authoritydaemon.js +6 -1
- package/dist_ts_interfaces/devices.d.ts +331 -0
- package/dist_ts_interfaces/devices.js +34 -0
- package/dist_ts_interfaces/index.d.ts +2 -0
- package/dist_ts_interfaces/index.js +3 -1
- package/dist_ts_interfaces/interfaces.d.ts +5 -3
- package/dist_ts_interfaces/interfaces.js +3 -2
- package/dist_ts_interfaces/management.d.ts +2 -2
- package/dist_ts_interfaces/management.js +2 -2
- package/dist_ts_interfaces/mcprequests.d.ts +1 -1
- package/dist_ts_interfaces/requests.d.ts +2 -2
- package/dist_ts_interfaces/requests.devices.d.ts +89 -0
- package/dist_ts_interfaces/requests.devices.js +2 -0
- package/dist_ts_interfaces/requests.upgrade.d.ts +0 -12
- package/package.json +12 -11
- package/readme.md +116 -24
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/aglapi/aglapisurface.document.ts +3 -3
- package/ts/classes.authmodels.ts +68 -25
- package/ts/classes.authstore.ts +183 -24
- package/ts/classes.cli.ts +38 -61
- package/ts/classes.config.ts +70 -21
- package/ts/classes.controller.ts +746 -329
- package/ts/classes.controllerdevices.ts +469 -0
- package/ts/classes.controllermanagement.ts +123 -49
- package/ts/classes.controllerservice.ts +3 -56
- package/ts/classes.mcpcontrollerhost.ts +10 -5
- package/ts/classes.processinspection.ts +84 -3
- package/ts/classes.proxycontrol.ts +2 -0
- package/ts/classes.proxydaemon.ts +3 -2
- package/ts/classes.proxystore.ts +4 -25
- package/ts/classes.sessionfeed.ts +13 -1
- package/ts/classes.tpmsecretcodec.ts +26 -0
- package/ts/classes.trustedproxysecrets.ts +317 -0
- package/ts/classes.upgradecoordinator.ts +33 -3
- package/ts/classes.upgradetransaction.ts +130 -1
- package/ts/classes.validation.ts +1 -1
- package/ts/functions.controlleradmission.ts +168 -0
- package/ts/functions.deviceapi.ts +295 -0
- package/ts/functions.deviceproof.ts +118 -0
- package/ts/functions.remotecli.ts +270 -0
- package/ts/functions.retiredenvironment.ts +25 -3
- package/ts/index.ts +1 -0
- package/ts/interfaces.auth.ts +41 -3
- package/ts/interfaces.config.ts +15 -0
- package/ts/interfaces.lifecycle.ts +3 -0
- package/ts_authswitch/classes.authoritydaemon.ts +2 -0
- package/ts_interfaces/devices.schema.json +890 -0
- package/ts_interfaces/devices.ts +392 -0
- package/ts_interfaces/index.ts +2 -0
- package/ts_interfaces/interfaces.ts +5 -2
- package/ts_interfaces/management.ts +2 -2
- package/ts_interfaces/mcprequests.ts +1 -1
- package/ts_interfaces/requests.devices.ts +95 -0
- package/ts_interfaces/requests.ts +10 -10
- package/ts_interfaces/requests.upgrade.ts +0 -16
- package/ts_web/00_commitinfo_data.ts +1 -1
- package/ts_web/classes.controllersocketclient.ts +27 -0
- package/ts_web/elements.devices.ts +752 -0
- package/ts_web/elements.harnesscontrollerapp.ts +18 -1
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
IControllerEvent,
|
|
3
|
+
IControllerMessageBundle,
|
|
4
|
+
IControllerPermission,
|
|
5
|
+
IControllerQuestion,
|
|
6
|
+
IControllerRuntimeId,
|
|
7
|
+
IControllerSessionFeedRow,
|
|
8
|
+
TControllerEventType,
|
|
9
|
+
TControllerSessionFeedDelta,
|
|
10
|
+
} from '../ts_interfaces/index.js';
|
|
11
|
+
import {
|
|
12
|
+
deviceLabelMaximumCharacters,
|
|
13
|
+
deviceMessageMaximumBytes,
|
|
14
|
+
type IDeviceMessage,
|
|
15
|
+
type IDevicePermission,
|
|
16
|
+
type IDeviceQuestion,
|
|
17
|
+
type IDeviceSessionFeedDelta,
|
|
18
|
+
type IDeviceSessionRow,
|
|
19
|
+
type IReq_DeviceAuthChallenge,
|
|
20
|
+
type IReq_DeviceAuthProve,
|
|
21
|
+
type IReq_DevicePair,
|
|
22
|
+
type IReq_DevicePermissionReply,
|
|
23
|
+
type IReq_DeviceQuestionReply,
|
|
24
|
+
type IReq_DeviceSessionRead,
|
|
25
|
+
type IReq_DeviceSessionSend,
|
|
26
|
+
type TDeviceEvent,
|
|
27
|
+
type TDeviceMessagePart,
|
|
28
|
+
} from '../ts_interfaces/devices.js';
|
|
29
|
+
import { isControllerSessionFeedRowId } from '../ts_interfaces/sessionfeed.js';
|
|
30
|
+
import { assertKeys, assertObject, assertQuestionAnswers } from './classes.validation.js';
|
|
31
|
+
import { sessionFeedRowId } from './classes.sessionfeed.js';
|
|
32
|
+
|
|
33
|
+
/*
|
|
34
|
+
* The device API's requests and projections: what a device may ask, checked before anything is read, and the reduced
|
|
35
|
+
* shapes of what it gets. A device sees the session feed without host paths, tickets or terminals, transcripts with
|
|
36
|
+
* tool calls reduced to name, title and status, and an allowlist of events.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/** The controller events a device receives, each projected by `deviceEvent`; every other event never reaches one. */
|
|
40
|
+
export const deviceRelayedEventTypes: ReadonlySet<TControllerEventType> = new Set<TControllerEventType>([
|
|
41
|
+
'sessionfeed.changed',
|
|
42
|
+
'sessions.changed',
|
|
43
|
+
'session.changed',
|
|
44
|
+
'session.history.changed',
|
|
45
|
+
'permissions.changed',
|
|
46
|
+
'session.text.updated',
|
|
47
|
+
'session.text.delta',
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
/** A feed row as a device sees it; none for a terminal row, which a device does not open. */
|
|
51
|
+
export const deviceSessionRow = (rowArg: IControllerSessionFeedRow): IDeviceSessionRow | undefined => (
|
|
52
|
+
rowArg.open.kind === 'terminal' ? undefined : {
|
|
53
|
+
id: rowArg.id,
|
|
54
|
+
harness: rowArg.harness,
|
|
55
|
+
state: rowArg.state,
|
|
56
|
+
name: rowArg.name,
|
|
57
|
+
...(rowArg.excerpt === undefined ? {} : { excerpt: rowArg.excerpt }),
|
|
58
|
+
updatedAt: rowArg.updatedAt,
|
|
59
|
+
}
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
export const deviceSessionRows = (rowsArg: readonly IControllerSessionFeedRow[]): IDeviceSessionRow[] => rowsArg
|
|
63
|
+
.flatMap((rowArg) => deviceSessionRow(rowArg) ?? []);
|
|
64
|
+
|
|
65
|
+
/** A feed change as a device applies it: the same epoch and revision, terminal rows left out. */
|
|
66
|
+
export const deviceFeedDelta = (deltaArg: TControllerSessionFeedDelta): IDeviceSessionFeedDelta => 'reset' in deltaArg
|
|
67
|
+
? { epoch: deltaArg.epoch, revision: deltaArg.revision, reset: true, upserts: [], removed: [] }
|
|
68
|
+
: {
|
|
69
|
+
epoch: deltaArg.epoch,
|
|
70
|
+
revision: deltaArg.revision,
|
|
71
|
+
reset: false,
|
|
72
|
+
upserts: deviceSessionRows(deltaArg.upserts),
|
|
73
|
+
removed: [...deltaArg.removed],
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/** One source message of a transcript as one device message: its reasoning, text and tool calls as parts, in order. */
|
|
77
|
+
const deviceMessage = (bundleArg: IControllerMessageBundle): IDeviceMessage | undefined => {
|
|
78
|
+
const first = bundleArg.messages[0];
|
|
79
|
+
if (!first) return undefined;
|
|
80
|
+
const parts: TDeviceMessagePart[] = [];
|
|
81
|
+
for (const message of bundleArg.messages) {
|
|
82
|
+
for (const reasoning of message.reasoning ?? []) {
|
|
83
|
+
if (reasoning.text !== '') parts.push({ type: 'reasoning', id: reasoning.id.nativeId, text: reasoning.text });
|
|
84
|
+
}
|
|
85
|
+
if (message.toolCall) {
|
|
86
|
+
parts.push({
|
|
87
|
+
type: 'tool',
|
|
88
|
+
id: message.toolCall.id.nativeId,
|
|
89
|
+
tool: message.toolCall.name,
|
|
90
|
+
...(message.toolCall.title === undefined ? {} : { title: message.toolCall.title }),
|
|
91
|
+
status: message.toolCall.status,
|
|
92
|
+
});
|
|
93
|
+
} else if (message.text !== '' || message.streaming === true) {
|
|
94
|
+
// A streaming part is listed while still empty: its live text applies to it.
|
|
95
|
+
parts.push({ type: 'text', id: message.id.nativeId, text: message.text });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
id: bundleArg.sourceMessageId.nativeId,
|
|
100
|
+
role: bundleArg.messages.some((messageArg) => messageArg.role === 'user') ? 'user' : 'assistant',
|
|
101
|
+
createdAt: first.createdAt,
|
|
102
|
+
parts,
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** A transcript page's messages, oldest first. */
|
|
107
|
+
export const deviceMessages = (bundlesArg: readonly IControllerMessageBundle[]): IDeviceMessage[] => bundlesArg
|
|
108
|
+
.flatMap((bundleArg) => deviceMessage(bundleArg) ?? []);
|
|
109
|
+
|
|
110
|
+
export const devicePermissions = (permissionsArg: readonly IControllerPermission[]): IDevicePermission[] => permissionsArg
|
|
111
|
+
.map((permissionArg) => ({
|
|
112
|
+
id: permissionArg.id.nativeId,
|
|
113
|
+
title: permissionArg.title,
|
|
114
|
+
type: permissionArg.type,
|
|
115
|
+
patterns: [...permissionArg.patterns],
|
|
116
|
+
}));
|
|
117
|
+
|
|
118
|
+
export const deviceQuestions = (questionsArg: readonly IControllerQuestion[]): IDeviceQuestion[] => questionsArg
|
|
119
|
+
.map((questionArg) => ({
|
|
120
|
+
id: questionArg.id.nativeId,
|
|
121
|
+
questions: questionArg.questions.map((itemArg) => ({
|
|
122
|
+
question: itemArg.question,
|
|
123
|
+
header: itemArg.header,
|
|
124
|
+
options: itemArg.options.map(({ label, description }) => ({ label, description })),
|
|
125
|
+
...(itemArg.multiple === undefined ? {} : { multiple: itemArg.multiple }),
|
|
126
|
+
...(itemArg.custom === undefined ? {} : { custom: itemArg.custom }),
|
|
127
|
+
})),
|
|
128
|
+
}));
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The row id a device names a conversation by, when the feed lists it as something a device opens; events about any
|
|
132
|
+
* other session (a driver, a child, a terminal's agent, one the feed has not listed yet) reach no device.
|
|
133
|
+
*/
|
|
134
|
+
const visibleRowId = (
|
|
135
|
+
sessionIdArg: IControllerRuntimeId | undefined,
|
|
136
|
+
rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
|
|
137
|
+
): string | undefined => {
|
|
138
|
+
if (!sessionIdArg || sessionIdArg.harnessId === 'controller') return undefined;
|
|
139
|
+
const rowId = sessionFeedRowId(sessionIdArg.harnessId, sessionIdArg.nativeId);
|
|
140
|
+
const row = rowOfArg(rowId);
|
|
141
|
+
return row && row.open.kind !== 'terminal' ? rowId : undefined;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
/** A controller event as a device receives it, or none. `rowOfArg` answers the feed's published rows. */
|
|
145
|
+
export const deviceEvent = (
|
|
146
|
+
eventArg: IControllerEvent,
|
|
147
|
+
rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
|
|
148
|
+
): TDeviceEvent | undefined => {
|
|
149
|
+
switch (eventArg.type) {
|
|
150
|
+
case 'sessionfeed.changed':
|
|
151
|
+
return eventArg.sessionFeed ? { type: 'sessionfeed.changed', delta: deviceFeedDelta(eventArg.sessionFeed) } : undefined;
|
|
152
|
+
case 'sessions.changed':
|
|
153
|
+
return { type: 'sessions.changed' };
|
|
154
|
+
case 'session.changed':
|
|
155
|
+
case 'session.history.changed':
|
|
156
|
+
case 'permissions.changed': {
|
|
157
|
+
if (!eventArg.sessionId) return eventArg.type === 'permissions.changed' ? { type: 'sessions.changed' } : undefined;
|
|
158
|
+
const sessionId = visibleRowId(eventArg.sessionId, rowOfArg);
|
|
159
|
+
return sessionId === undefined ? undefined : { type: 'session.changed', sessionId };
|
|
160
|
+
}
|
|
161
|
+
case 'session.text.updated': {
|
|
162
|
+
const update = eventArg.textUpdate;
|
|
163
|
+
const sessionId = visibleRowId(update?.sessionId, rowOfArg);
|
|
164
|
+
return update && sessionId !== undefined ? {
|
|
165
|
+
type: 'session.text.updated',
|
|
166
|
+
update: { sessionId, messageId: update.messageId.nativeId, partId: update.partId.nativeId, text: update.text },
|
|
167
|
+
} : undefined;
|
|
168
|
+
}
|
|
169
|
+
case 'session.text.delta': {
|
|
170
|
+
const delta = eventArg.textDelta;
|
|
171
|
+
const sessionId = visibleRowId(delta?.sessionId, rowOfArg);
|
|
172
|
+
return delta && sessionId !== undefined ? {
|
|
173
|
+
type: 'session.text.delta',
|
|
174
|
+
delta: {
|
|
175
|
+
sessionId,
|
|
176
|
+
messageId: delta.messageId.nativeId,
|
|
177
|
+
partId: delta.partId.nativeId,
|
|
178
|
+
delta: delta.delta,
|
|
179
|
+
baseTextUtf8Bytes: delta.baseTextUtf8Bytes,
|
|
180
|
+
textUtf8Bytes: delta.textUtf8Bytes,
|
|
181
|
+
},
|
|
182
|
+
} : undefined;
|
|
183
|
+
}
|
|
184
|
+
default:
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const assertText = (valueArg: unknown, nameArg: string, maximumBytesArg: number): string => {
|
|
190
|
+
if (typeof valueArg !== 'string' || valueArg.length === 0 || Buffer.byteLength(valueArg, 'utf8') > maximumBytesArg) {
|
|
191
|
+
throw new Error(`${nameArg} must contain 1-${maximumBytesArg} UTF-8 bytes.`);
|
|
192
|
+
}
|
|
193
|
+
return valueArg;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const assertDeviceId = (valueArg: unknown): string => {
|
|
197
|
+
if (typeof valueArg !== 'string' || !/^[A-Za-z0-9_-]{24}$/u.test(valueArg)) throw new Error('deviceId is not a device id.');
|
|
198
|
+
return valueArg;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const assertRowId = (valueArg: unknown): string => {
|
|
202
|
+
if (!isControllerSessionFeedRowId(valueArg)) throw new Error('sessionId must name a session as the session feed does.');
|
|
203
|
+
return valueArg;
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/** A device's name or model: one line of 1 to 64 characters, its surrounding blanks dropped. */
|
|
207
|
+
const assertDeviceLabel = (valueArg: unknown, nameArg: string): string => {
|
|
208
|
+
const label = typeof valueArg === 'string' ? valueArg.trim() : '';
|
|
209
|
+
if (label.length === 0 || [...label].length > deviceLabelMaximumCharacters || /\p{Cc}/u.test(label)) {
|
|
210
|
+
throw new Error(`${nameArg} must be one line of 1-${deviceLabelMaximumCharacters} characters.`);
|
|
211
|
+
}
|
|
212
|
+
return label;
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
export const assertDevicePairRequest = (valueArg: unknown): IReq_DevicePair['request'] => {
|
|
216
|
+
const value = assertObject(valueArg, 'device pair request');
|
|
217
|
+
assertKeys(value, ['code', 'name', 'model', 'publicKey', 'proof']);
|
|
218
|
+
return {
|
|
219
|
+
code: assertText(value.code, 'code', 64),
|
|
220
|
+
name: assertDeviceLabel(value.name, 'name'),
|
|
221
|
+
model: assertDeviceLabel(value.model, 'model'),
|
|
222
|
+
publicKey: assertText(value.publicKey, 'publicKey', 256),
|
|
223
|
+
proof: assertText(value.proof, 'proof', 128),
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
export const assertDeviceAuthChallengeRequest = (valueArg: unknown): IReq_DeviceAuthChallenge['request'] => {
|
|
228
|
+
const value = assertObject(valueArg, 'device challenge request');
|
|
229
|
+
assertKeys(value, ['deviceId']);
|
|
230
|
+
return { deviceId: assertDeviceId(value.deviceId) };
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
export const assertDeviceAuthProveRequest = (valueArg: unknown): IReq_DeviceAuthProve['request'] => {
|
|
234
|
+
const value = assertObject(valueArg, 'device proof request');
|
|
235
|
+
assertKeys(value, ['deviceId', 'signature']);
|
|
236
|
+
return { deviceId: assertDeviceId(value.deviceId), signature: assertText(value.signature, 'signature', 128) };
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
export const assertDeviceSessionReadRequest = (valueArg: unknown): IReq_DeviceSessionRead['request'] => {
|
|
240
|
+
const value = assertObject(valueArg, 'device session read request');
|
|
241
|
+
assertKeys(value, ['sessionId'], ['before', 'limit']);
|
|
242
|
+
if (value.limit !== undefined && (!Number.isSafeInteger(value.limit) || (value.limit as number) < 1 || (value.limit as number) > 50)) {
|
|
243
|
+
throw new Error('limit must be an integer from 1 to 50.');
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
sessionId: assertRowId(value.sessionId),
|
|
247
|
+
...(value.before === undefined ? {} : { before: assertText(value.before, 'before', 4096) }),
|
|
248
|
+
...(value.limit === undefined ? {} : { limit: value.limit as number }),
|
|
249
|
+
};
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
export const assertDeviceSessionSendRequest = (valueArg: unknown): IReq_DeviceSessionSend['request'] => {
|
|
253
|
+
const value = assertObject(valueArg, 'device session send request');
|
|
254
|
+
assertKeys(value, ['sessionId', 'text']);
|
|
255
|
+
const text = assertText(value.text, 'text', deviceMessageMaximumBytes);
|
|
256
|
+
if (!text.trim() || text.includes('\0')) throw new Error('text must be a message that is not blank.');
|
|
257
|
+
return { sessionId: assertRowId(value.sessionId), text };
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
export const assertDevicePermissionReplyRequest = (valueArg: unknown): IReq_DevicePermissionReply['request'] => {
|
|
261
|
+
const value = assertObject(valueArg, 'device permission reply request');
|
|
262
|
+
assertKeys(value, ['sessionId', 'permissionId', 'reply'], ['message']);
|
|
263
|
+
if (value.reply !== 'once' && value.reply !== 'reject') throw new Error('reply must be once or reject.');
|
|
264
|
+
return {
|
|
265
|
+
sessionId: assertRowId(value.sessionId),
|
|
266
|
+
permissionId: assertText(value.permissionId, 'permissionId', 512),
|
|
267
|
+
reply: value.reply,
|
|
268
|
+
...(value.message === undefined ? {} : { message: assertText(value.message, 'message', 2048) }),
|
|
269
|
+
};
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
export const assertDeviceQuestionReplyRequest = (valueArg: unknown): IReq_DeviceQuestionReply['request'] => {
|
|
273
|
+
const value = assertObject(valueArg, 'device question reply request');
|
|
274
|
+
assertKeys(value, ['sessionId', 'questionId', 'answers']);
|
|
275
|
+
return {
|
|
276
|
+
sessionId: assertRowId(value.sessionId),
|
|
277
|
+
questionId: assertText(value.questionId, 'questionId', 512),
|
|
278
|
+
answers: assertQuestionAnswers(value.answers),
|
|
279
|
+
};
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
export const assertDevicePairingCancelRequest = (valueArg: unknown): { pairingId: string } => {
|
|
283
|
+
const value = assertObject(valueArg, 'pairing cancel request');
|
|
284
|
+
assertKeys(value, ['pairingId']);
|
|
285
|
+
if (typeof value.pairingId !== 'string' || !/^[A-Za-z0-9_-]{22}$/u.test(value.pairingId)) {
|
|
286
|
+
throw new Error('pairingId is not a pairing id.');
|
|
287
|
+
}
|
|
288
|
+
return { pairingId: value.pairingId };
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
export const assertDeviceRevokeRequest = (valueArg: unknown): { deviceId: string } => {
|
|
292
|
+
const value = assertObject(valueArg, 'device revoke request');
|
|
293
|
+
assertKeys(value, ['deviceId']);
|
|
294
|
+
return { deviceId: assertDeviceId(value.deviceId) };
|
|
295
|
+
};
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import {
|
|
3
|
+
deviceAuthenticationMessageLabel,
|
|
4
|
+
devicePairingMessageLabel,
|
|
5
|
+
devicePairingScheme,
|
|
6
|
+
deviceSecretBytes,
|
|
7
|
+
} from '../ts_interfaces/devices.js';
|
|
8
|
+
|
|
9
|
+
/*
|
|
10
|
+
* The cryptography of the device protocol (`ts_interfaces/devices.ts`): the messages a device key signs, the P-256 key
|
|
11
|
+
* and signature checks, the fingerprint people compare, and the pairing payload of the QR code. Everything runs on
|
|
12
|
+
* `node:crypto`; the signed messages are byte for byte what HarnessKit's `DeviceProof` builds.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Everything of a P-256 SubjectPublicKeyInfo in DER before the uncompressed point's 64 bytes. */
|
|
16
|
+
const p256SpkiPrefix = Buffer.from('3059301306072a8648ce3d020106082a8648ce3d03010703420004', 'hex');
|
|
17
|
+
const p256SpkiBytes = p256SpkiPrefix.byteLength + 64;
|
|
18
|
+
const base64UrlPattern = /^[A-Za-z0-9_-]+$/u;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The bytes of a base64url text without padding, refused (undefined) unless it is exactly that text's canonical form,
|
|
22
|
+
* of `byteLengthArg` bytes when given and of at most `maximumBytesArg` otherwise.
|
|
23
|
+
*/
|
|
24
|
+
export const decodeDeviceBase64Url = (
|
|
25
|
+
valueArg: unknown,
|
|
26
|
+
sizeArg: { bytes: number } | { maximumBytes: number },
|
|
27
|
+
): Buffer | undefined => {
|
|
28
|
+
if (typeof valueArg !== 'string' || !base64UrlPattern.test(valueArg)) return undefined;
|
|
29
|
+
const maximum = 'bytes' in sizeArg ? sizeArg.bytes : sizeArg.maximumBytes;
|
|
30
|
+
if (valueArg.length > Math.ceil((maximum * 4) / 3)) return undefined;
|
|
31
|
+
const bytes = Buffer.from(valueArg, 'base64url');
|
|
32
|
+
if (bytes.toString('base64url') !== valueArg) return undefined;
|
|
33
|
+
if ('bytes' in sizeArg ? bytes.byteLength !== sizeArg.bytes : bytes.byteLength === 0) return undefined;
|
|
34
|
+
return bytes;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** A signed message: each field as a 4-byte big-endian length followed by its bytes. */
|
|
38
|
+
const signedMessage = (fieldsArg: readonly Uint8Array[]): Buffer => Buffer.concat(fieldsArg.flatMap((fieldArg) => {
|
|
39
|
+
const length = Buffer.alloc(4);
|
|
40
|
+
length.writeUInt32BE(fieldArg.byteLength);
|
|
41
|
+
return [length, fieldArg];
|
|
42
|
+
}));
|
|
43
|
+
|
|
44
|
+
export interface IDeviceMessageBinding {
|
|
45
|
+
/** `controller:<port>`. */
|
|
46
|
+
controllerId: string;
|
|
47
|
+
/** The controller's public origin, exactly as it is configured. */
|
|
48
|
+
origin: string;
|
|
49
|
+
/** The device key, SubjectPublicKeyInfo DER. */
|
|
50
|
+
publicKey: Uint8Array;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The message a device signs to pair: it binds the key to this controller, origin and code. */
|
|
54
|
+
export const devicePairingMessage = (bindingArg: IDeviceMessageBinding, codeArg: Uint8Array): Buffer => signedMessage([
|
|
55
|
+
Buffer.from(devicePairingMessageLabel, 'utf8'),
|
|
56
|
+
Buffer.from(bindingArg.controllerId, 'utf8'),
|
|
57
|
+
Buffer.from(bindingArg.origin, 'utf8'),
|
|
58
|
+
plugins.crypto.createHash('sha256').update(codeArg).digest(),
|
|
59
|
+
bindingArg.publicKey,
|
|
60
|
+
]);
|
|
61
|
+
|
|
62
|
+
/** The message a device signs to authenticate one connection: it binds the key to this controller, origin and nonce. */
|
|
63
|
+
export const deviceAuthenticationMessage = (bindingArg: IDeviceMessageBinding, nonceArg: Uint8Array): Buffer => {
|
|
64
|
+
if (nonceArg.byteLength !== deviceSecretBytes) throw new Error(`A device nonce is ${deviceSecretBytes} bytes.`);
|
|
65
|
+
return signedMessage([
|
|
66
|
+
Buffer.from(deviceAuthenticationMessageLabel, 'utf8'),
|
|
67
|
+
Buffer.from(bindingArg.controllerId, 'utf8'),
|
|
68
|
+
Buffer.from(bindingArg.origin, 'utf8'),
|
|
69
|
+
nonceArg,
|
|
70
|
+
bindingArg.publicKey,
|
|
71
|
+
]);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A device's public key: a P-256 SubjectPublicKeyInfo in DER with an uncompressed point on the curve, in exactly the
|
|
76
|
+
* form `node:crypto` exports it again, so one key has one text and one fingerprint. Undefined for anything else.
|
|
77
|
+
*/
|
|
78
|
+
export const importDevicePublicKey = (spkiArg: Uint8Array): plugins.crypto.KeyObject | undefined => {
|
|
79
|
+
const spki = Buffer.from(spkiArg);
|
|
80
|
+
if (spki.byteLength !== p256SpkiBytes || !spki.subarray(0, p256SpkiPrefix.byteLength).equals(p256SpkiPrefix)) {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
let key: plugins.crypto.KeyObject;
|
|
84
|
+
try {
|
|
85
|
+
key = plugins.crypto.createPublicKey({ key: spki, format: 'der', type: 'spki' });
|
|
86
|
+
} catch {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') return undefined;
|
|
90
|
+
return key.export({ format: 'der', type: 'spki' }).equals(spki) ? key : undefined;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** Whether `signatureArg` (ECDSA P-256 with SHA-256, DER) is the key's signature of `messageArg`. */
|
|
94
|
+
export const verifyDeviceSignature = (
|
|
95
|
+
keyArg: plugins.crypto.KeyObject,
|
|
96
|
+
messageArg: Uint8Array,
|
|
97
|
+
signatureArg: Uint8Array,
|
|
98
|
+
): boolean => {
|
|
99
|
+
try {
|
|
100
|
+
return plugins.crypto.verify('sha256', messageArg, { key: keyArg, dsaEncoding: 'der' }, signatureArg);
|
|
101
|
+
} catch {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** A key's fingerprint for people to compare: SHA-256 of the SPKI, the first 16 bytes as 8 groups of 4 uppercase hex. */
|
|
107
|
+
export const deviceKeyFingerprint = (spkiArg: Uint8Array): string => plugins.crypto.createHash('sha256').update(spkiArg)
|
|
108
|
+
.digest().subarray(0, 16).toString('hex').toUpperCase().match(/.{4}/gu)!.join(' ');
|
|
109
|
+
|
|
110
|
+
/** Percent-encodes everything in a query value but letters, digits and `-._~`, as HarnessKit's payload writer does. */
|
|
111
|
+
const queryValue = (valueArg: string): string => encodeURIComponent(valueArg)
|
|
112
|
+
.replace(/[!'()*]/gu, (characterArg) => `%${characterArg.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
113
|
+
|
|
114
|
+
/** The QR code's payload: `agl-pair:?origin=<https origin>&controller=<controller id>&code=<base64url>`, each once. */
|
|
115
|
+
export const devicePairingPayload = (originArg: string, controllerIdArg: string, codeArg: Uint8Array): string => (
|
|
116
|
+
`${devicePairingScheme}:?origin=${queryValue(originArg)}&controller=${queryValue(controllerIdArg)}`
|
|
117
|
+
+ `&code=${Buffer.from(codeArg).toString('base64url')}`
|
|
118
|
+
);
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import {
|
|
3
|
+
defaultControllerPort,
|
|
4
|
+
resolveMovedRuntimeConfig,
|
|
5
|
+
resolveStoredRuntimeConfig,
|
|
6
|
+
} from './classes.config.js';
|
|
7
|
+
import { acquireStartAdmission, withControllerAuthStore } from './classes.cli.js';
|
|
8
|
+
import type { SmartDataAuthStore } from './classes.authstore.js';
|
|
9
|
+
import { TpmSecretCodec, type ITpmSecretCodec } from './classes.tpmsecretcodec.js';
|
|
10
|
+
import {
|
|
11
|
+
decodeTrustedProxySecret,
|
|
12
|
+
importControllerTrustedProxySecret,
|
|
13
|
+
removeControllerTrustedProxySecret,
|
|
14
|
+
} from './classes.trustedproxysecrets.js';
|
|
15
|
+
import { configurationLocalCliActor } from './functions.configurationactor.js';
|
|
16
|
+
import { preflightAGLHomeMigration } from './functions.controllerdataroot.js';
|
|
17
|
+
import type { IControllerIssuerIdentity } from './interfaces.identity.js';
|
|
18
|
+
import type { IControllerRuntimeConfig } from './interfaces.config.js';
|
|
19
|
+
import type { IControllerAuditRemoteMove, TControllerAuditEventType } from './interfaces.auth.js';
|
|
20
|
+
|
|
21
|
+
export const remoteCliHelp = `Usage: agl remote set --public-origin ORIGIN [--rp-id HOST] [--gateway-source ADDRESS]... [--port PORT]
|
|
22
|
+
agl remote unset [--port PORT]
|
|
23
|
+
agl remote secret import [--port PORT] < SECRET_FILE
|
|
24
|
+
Every command runs against a stopped controller (agl stop first) on the port it was initialized on (default 4097),
|
|
25
|
+
as the local OS user, and is audited.
|
|
26
|
+
set moves the port to the HTTPS public origin ORIGIN behind a TLS reverse proxy, with WebAuthn RP ID HOST (default:
|
|
27
|
+
the origin's hostname). Each --gateway-source names an address the proxy reaches this host from; without one only a
|
|
28
|
+
reverse proxy on this host reaches the controller, which then listens on loopback. The controller keeps its id and
|
|
29
|
+
all of its data. When the origin or RP ID changes, its passkey is removed and every temporary password revoked: the
|
|
30
|
+
next start prints a new setup code, to enroll a passkey at the new origin. When the origin changes, every paired
|
|
31
|
+
device is removed as well (a device signs the origin it paired with). Run it again to change the gateway sources;
|
|
32
|
+
the passkey and the devices then stay.
|
|
33
|
+
unset moves the port back to http://localhost:PORT (RP ID localhost), removes the passkey and every paired device,
|
|
34
|
+
revokes every temporary password and forgets the trusted-proxy secret.
|
|
35
|
+
secret import reads a 32-byte base64url secret (43 characters) from standard input, never from a terminal, and makes
|
|
36
|
+
it the controller's trusted-proxy secret, for a reverse proxy other than AGL's own gateway: that proxy injects it as
|
|
37
|
+
X-Harness-Controller-Proxy-Secret. The secret is sealed with the TPM and never printed.
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
export type TRemoteCliArguments =
|
|
41
|
+
| { action: 'set'; port: number; publicOrigin: string; rpId?: string; gatewaySources: string[] }
|
|
42
|
+
| { action: 'unset'; port: number }
|
|
43
|
+
| { action: 'secret-import'; port: number };
|
|
44
|
+
|
|
45
|
+
export const parseRemoteCliArguments = (argsArg: readonly string[]): TRemoteCliArguments => {
|
|
46
|
+
const rest = [...argsArg];
|
|
47
|
+
const first = rest.shift();
|
|
48
|
+
const action = first === 'secret' && rest[0] === 'import' ? (rest.shift(), 'secret-import' as const)
|
|
49
|
+
: first === 'set' || first === 'unset' ? first : undefined;
|
|
50
|
+
if (!action) throw new Error(remoteCliHelp);
|
|
51
|
+
let port = defaultControllerPort;
|
|
52
|
+
let publicOrigin: string | undefined;
|
|
53
|
+
let rpId: string | undefined;
|
|
54
|
+
const gatewaySources: string[] = [];
|
|
55
|
+
const seen = new Set<string>();
|
|
56
|
+
for (let index = 0; index < rest.length; index++) {
|
|
57
|
+
const token = rest[index]!;
|
|
58
|
+
const equals = token.startsWith('--') ? token.indexOf('=') : -1;
|
|
59
|
+
const flag = equals > 0 ? token.slice(0, equals) : token;
|
|
60
|
+
if (flag !== '--gateway-source' && seen.has(flag)) throw new Error(`Duplicate remote option: ${flag}.`);
|
|
61
|
+
seen.add(flag);
|
|
62
|
+
const value = equals > 0 ? token.slice(equals + 1) : rest[++index];
|
|
63
|
+
if (value === undefined || value === '' || (equals < 0 && value.startsWith('--'))) {
|
|
64
|
+
throw new Error(`${flag} requires a value.`);
|
|
65
|
+
}
|
|
66
|
+
if (flag === '--port') { port = Number(value); continue; }
|
|
67
|
+
if (action === 'set' && flag === '--public-origin') { publicOrigin = value; continue; }
|
|
68
|
+
if (action === 'set' && flag === '--rp-id') { rpId = value; continue; }
|
|
69
|
+
if (action === 'set' && flag === '--gateway-source') { gatewaySources.push(value); continue; }
|
|
70
|
+
throw new Error(`Unknown remote option: ${flag}.`);
|
|
71
|
+
}
|
|
72
|
+
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.');
|
|
73
|
+
if (action !== 'set') return { action, port };
|
|
74
|
+
if (publicOrigin === undefined) throw new Error('agl remote set requires --public-origin.');
|
|
75
|
+
return { action, port, publicOrigin, ...(rpId === undefined ? {} : { rpId }), gatewaySources };
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export interface IRemoteCliOptions {
|
|
79
|
+
/** Seals the trusted-proxy secret; TPM2 when absent. For tests. */
|
|
80
|
+
codec?: ITpmSecretCodec;
|
|
81
|
+
/** Where `secret import` reads the secret; this process's standard input when absent. */
|
|
82
|
+
input?: NodeJS.ReadableStream & { isTTY?: boolean };
|
|
83
|
+
/** Where the outcome is written; standard output when absent. */
|
|
84
|
+
write?: (textArg: string) => void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A trusted-proxy secret file is a few dozen bytes; anything past this is not one. */
|
|
88
|
+
const maximumSecretInputBytes = 4_096;
|
|
89
|
+
|
|
90
|
+
const readSecretInput = async (inputArg: NodeJS.ReadableStream & { isTTY?: boolean }): Promise<string> => {
|
|
91
|
+
if (inputArg.isTTY) {
|
|
92
|
+
throw new Error('agl remote secret import reads the secret from a pipe or a file, never from a terminal: '
|
|
93
|
+
+ 'run it as `agl remote secret import --port <port> < SECRET_FILE`.');
|
|
94
|
+
}
|
|
95
|
+
const chunks: Buffer[] = [];
|
|
96
|
+
let bytes = 0;
|
|
97
|
+
try {
|
|
98
|
+
for await (const chunk of inputArg) {
|
|
99
|
+
const buffer = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk as Uint8Array);
|
|
100
|
+
chunks.push(buffer);
|
|
101
|
+
bytes += buffer.byteLength;
|
|
102
|
+
if (bytes > maximumSecretInputBytes) throw new Error('The standard input is longer than a trusted-proxy secret.');
|
|
103
|
+
}
|
|
104
|
+
return Buffer.concat(chunks).toString('utf8').trim();
|
|
105
|
+
} finally {
|
|
106
|
+
for (const chunk of chunks) chunk.fill(0);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Holds the controller's port on loopback while a command changes its stopped configuration: a controller still
|
|
112
|
+
* listening there (on loopback or every interface) is found, and one starting meanwhile cannot listen until the
|
|
113
|
+
* command ends.
|
|
114
|
+
*/
|
|
115
|
+
const holdStoppedControllerPort = async (portArg: number): Promise<plugins.net.Server> => {
|
|
116
|
+
const server = plugins.net.createServer((socketArg) => socketArg.destroy());
|
|
117
|
+
try {
|
|
118
|
+
await new Promise<void>((resolve, reject) => {
|
|
119
|
+
server.once('error', reject);
|
|
120
|
+
server.listen({ host: '127.0.0.1', port: portArg, exclusive: true }, () => {
|
|
121
|
+
server.off('error', reject);
|
|
122
|
+
resolve();
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
} catch (errorArg) {
|
|
126
|
+
server.close();
|
|
127
|
+
if ((errorArg as NodeJS.ErrnoException).code === 'EADDRINUSE') {
|
|
128
|
+
throw new Error(`Port ${portArg} is in use: agl remote changes a stopped controller only. Stop it with `
|
|
129
|
+
+ `\`agl stop --port ${portArg}\` and run this again.`);
|
|
130
|
+
}
|
|
131
|
+
throw errorArg;
|
|
132
|
+
}
|
|
133
|
+
return server;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const releasePort = (serverArg: plugins.net.Server): Promise<void> => new Promise((resolve) => {
|
|
137
|
+
serverArg.close(() => resolve());
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
interface IStoppedController {
|
|
141
|
+
authStore: SmartDataAuthStore;
|
|
142
|
+
issuer: IControllerIssuerIdentity;
|
|
143
|
+
/** `controller:<port>`. */
|
|
144
|
+
controllerId: string;
|
|
145
|
+
config: IControllerRuntimeConfig;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Runs `actionArg` on the stored configuration of a stopped, initialized controller, under start admission. */
|
|
149
|
+
const withStoppedController = async <T>(
|
|
150
|
+
portArg: number,
|
|
151
|
+
actionArg: (controllerArg: IStoppedController) => Promise<T>,
|
|
152
|
+
): Promise<T> => {
|
|
153
|
+
await preflightAGLHomeMigration();
|
|
154
|
+
const lease = await acquireStartAdmission('remote');
|
|
155
|
+
try {
|
|
156
|
+
const port = await holdStoppedControllerPort(portArg);
|
|
157
|
+
try {
|
|
158
|
+
return await withControllerAuthStore('The remote configuration change', async (authStoreArg, issuerArg) => {
|
|
159
|
+
const stored = await authStoreArg.getRuntimeConfig(portArg);
|
|
160
|
+
if (!stored) {
|
|
161
|
+
throw new Error(`No controller configuration exists for port ${portArg}. Start the controller on that port `
|
|
162
|
+
+ 'once first, with the same AGL_HOME, AGL_DB_DIR or AGL_MONGO_URL / AGL_MONGO_DB environment.');
|
|
163
|
+
}
|
|
164
|
+
const config = await resolveStoredRuntimeConfig(stored, { controllerPort: portArg });
|
|
165
|
+
return actionArg({ authStore: authStoreArg, issuer: issuerArg, controllerId: `controller:${portArg}`, config });
|
|
166
|
+
});
|
|
167
|
+
} finally {
|
|
168
|
+
await releasePort(port);
|
|
169
|
+
}
|
|
170
|
+
} finally {
|
|
171
|
+
await lease?.release();
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Records `typeArg` as attempted, runs the change, and records its outcome, attributed to this OS user and process;
|
|
177
|
+
* a move records on every event where it goes from and to (`details.remoteMove`).
|
|
178
|
+
*/
|
|
179
|
+
const audited = async <T>(
|
|
180
|
+
authStoreArg: SmartDataAuthStore,
|
|
181
|
+
typeArg: TControllerAuditEventType,
|
|
182
|
+
actionArg: () => Promise<T>,
|
|
183
|
+
remoteMoveArg?: IControllerAuditRemoteMove,
|
|
184
|
+
): Promise<T> => {
|
|
185
|
+
const localCli = await configurationLocalCliActor();
|
|
186
|
+
const detail = { localCli, ...(remoteMoveArg === undefined ? {} : { details: { remoteMove: remoteMoveArg } }) };
|
|
187
|
+
await authStoreArg.recordAuditEvent({ type: typeArg, outcome: 'attempted', ...detail });
|
|
188
|
+
let result: T;
|
|
189
|
+
try {
|
|
190
|
+
result = await actionArg();
|
|
191
|
+
} catch (errorArg) {
|
|
192
|
+
try {
|
|
193
|
+
await authStoreArg.recordAuditEvent({ type: typeArg, outcome: 'failed', ...detail });
|
|
194
|
+
} catch (auditErrorArg) {
|
|
195
|
+
throw new AggregateError([errorArg, auditErrorArg], 'The change failed and its failure could not be audited.', { cause: errorArg });
|
|
196
|
+
}
|
|
197
|
+
throw errorArg;
|
|
198
|
+
}
|
|
199
|
+
await authStoreArg.recordAuditEvent({ type: typeArg, outcome: 'succeeded', ...detail });
|
|
200
|
+
return result;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const describeConfig = (configArg: IControllerRuntimeConfig): string => configArg.tlsMode === 'local'
|
|
204
|
+
? `${configArg.publicOrigin} (RP ID ${configArg.rpId}, local)`
|
|
205
|
+
: `${configArg.publicOrigin} (RP ID ${configArg.rpId}, behind a TLS reverse proxy, gateway sources: `
|
|
206
|
+
+ `${configArg.gatewaySources?.join(', ') ?? 'none, only a reverse proxy on this host'})`;
|
|
207
|
+
|
|
208
|
+
const moveOutcome = (
|
|
209
|
+
controllerIdArg: string,
|
|
210
|
+
previousArg: IControllerRuntimeConfig,
|
|
211
|
+
targetArg: IControllerRuntimeConfig,
|
|
212
|
+
enrollmentResetArg: boolean,
|
|
213
|
+
devicesRemovedArg: number,
|
|
214
|
+
): string => [
|
|
215
|
+
`Moved ${controllerIdArg} from ${describeConfig(previousArg)} to ${describeConfig(targetArg)}.`,
|
|
216
|
+
...(enrollmentResetArg
|
|
217
|
+
? [`Its passkey was removed and every temporary password revoked. The next \`agl start --port ${targetArg.controllerPort}\` `
|
|
218
|
+
+ `prints a setup code: enroll a passkey with it at ${targetArg.publicOrigin}.`]
|
|
219
|
+
: ['Its passkey stays: the origin and RP ID did not change.']),
|
|
220
|
+
...(devicesRemovedArg > 0
|
|
221
|
+
? [`${devicesRemovedArg === 1 ? 'Its paired device was' : `Its ${devicesRemovedArg} paired devices were`} removed: a device `
|
|
222
|
+
+ 'signs the origin it paired with. Pair it again in Settings → Devices once the controller has a public origin.']
|
|
223
|
+
: []),
|
|
224
|
+
...(targetArg.gatewaySources
|
|
225
|
+
? [`Let only ${targetArg.gatewaySources.join(', ')} reach port ${targetArg.controllerPort} through the host firewall.`]
|
|
226
|
+
: []),
|
|
227
|
+
].join('\n') + '\n';
|
|
228
|
+
|
|
229
|
+
export const runRemoteCli = async (argsArg: string[], optionsArg: IRemoteCliOptions = {}): Promise<void> => {
|
|
230
|
+
const write = optionsArg.write ?? ((textArg: string) => { process.stdout.write(textArg); });
|
|
231
|
+
if (argsArg.includes('--help') || argsArg.includes('-h')) { write(remoteCliHelp); return; }
|
|
232
|
+
const parsed = parseRemoteCliArguments(argsArg);
|
|
233
|
+
if (parsed.action === 'secret-import') {
|
|
234
|
+
const secret = await readSecretInput(optionsArg.input ?? process.stdin);
|
|
235
|
+
decodeTrustedProxySecret(secret).fill(0);
|
|
236
|
+
const outcome = await withStoppedController(parsed.port, async (controllerArg) => {
|
|
237
|
+
if (controllerArg.config.tlsMode !== 'proxy') {
|
|
238
|
+
throw new Error(`${controllerArg.controllerId} runs on localhost, which takes no trusted-proxy secret: move it `
|
|
239
|
+
+ 'behind the reverse proxy with `agl remote set` first.');
|
|
240
|
+
}
|
|
241
|
+
return audited(controllerArg.authStore, 'remote.secret.import', () => importControllerTrustedProxySecret({
|
|
242
|
+
controllerId: controllerArg.controllerId,
|
|
243
|
+
issuerId: controllerArg.issuer.issuerId,
|
|
244
|
+
codec: optionsArg.codec ?? new TpmSecretCodec(),
|
|
245
|
+
secret,
|
|
246
|
+
}));
|
|
247
|
+
});
|
|
248
|
+
write(`Imported the trusted-proxy secret of controller:${parsed.port} (generation ${outcome.generation}). `
|
|
249
|
+
+ 'Its reverse proxy must send it as X-Harness-Controller-Proxy-Secret.\n');
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
write(await withStoppedController(parsed.port, async (controllerArg) => {
|
|
253
|
+
const target = resolveMovedRuntimeConfig(controllerArg.config, parsed.action === 'set'
|
|
254
|
+
? { publicOrigin: parsed.publicOrigin, ...(parsed.rpId === undefined ? {} : { rpId: parsed.rpId }), gatewaySources: parsed.gatewaySources }
|
|
255
|
+
: 'local');
|
|
256
|
+
const type = parsed.action === 'set' ? 'remote.set' as const : 'remote.unset' as const;
|
|
257
|
+
const moved = await audited(controllerArg.authStore, type, async () => {
|
|
258
|
+
const result = await controllerArg.authStore.moveRuntimeConfig(target);
|
|
259
|
+
// Local mode takes no trusted-proxy secret, and moving back behind a proxy generates a new one.
|
|
260
|
+
if (parsed.action === 'unset') await removeControllerTrustedProxySecret(controllerArg.controllerId);
|
|
261
|
+
return result;
|
|
262
|
+
}, {
|
|
263
|
+
previous: { publicOrigin: controllerArg.config.publicOrigin, rpId: controllerArg.config.rpId },
|
|
264
|
+
target: { publicOrigin: target.publicOrigin, rpId: target.rpId },
|
|
265
|
+
});
|
|
266
|
+
return moved.changed
|
|
267
|
+
? moveOutcome(controllerArg.controllerId, moved.previous, target, moved.enrollmentReset, moved.devicesRemoved)
|
|
268
|
+
: `${controllerArg.controllerId} already serves ${describeConfig(target)}; nothing changed.\n`;
|
|
269
|
+
}));
|
|
270
|
+
};
|