@agentknight/client 0.9.49 → 0.9.51
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/LICENSE +201 -201
- package/README.md +356 -341
- package/dist/chunks/aad-relay-login-NABH6HML.js +14 -0
- package/dist/chunks/{chunk-OZKXJ6L4.js → chunk-HWCSV7QP.js} +1305 -1087
- package/dist/chunks/{chunk-NHA7HI6P.js → chunk-WS6ISEXX.js} +1 -1
- package/dist/chunks/chunk-XODJ7TIT.js +475 -0
- package/dist/chunks/{local-sessions-EZUANCR4.js → local-sessions-CLY45IWB.js} +1 -1
- package/dist/chunks/start-client-XMBDUDJZ.js +3971 -0
- package/dist/cli.js +12 -5
- package/dist/upgrade-worker.js +200 -4
- package/package.json +14 -6
- package/dist/chunks/start-client-C3PK6POG.js +0 -3428
|
@@ -18,7 +18,7 @@ function toErrorDetails(error) {
|
|
|
18
18
|
// src/app-version.ts
|
|
19
19
|
import { readFileSync } from "node:fs";
|
|
20
20
|
function readAppVersion() {
|
|
21
|
-
if (true) return "0.9.
|
|
21
|
+
if (true) return "0.9.51";
|
|
22
22
|
const metadata = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
23
23
|
if (typeof metadata !== "object" || metadata === null || !("version" in metadata) || typeof metadata.version !== "string" || metadata.version.length === 0) {
|
|
24
24
|
throw new Error("AgentKnight package metadata does not contain a version");
|
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
AadAccountResultSchema,
|
|
4
|
+
AuthUserSchema,
|
|
5
|
+
PcEnrollmentIdSchema,
|
|
6
|
+
PcEnrollmentStartRequestSchema,
|
|
7
|
+
PcEnrollmentVerifierRequestSchema
|
|
8
|
+
} from "./chunk-HWCSV7QP.js";
|
|
9
|
+
|
|
10
|
+
// src/aad-relay-login.ts
|
|
11
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
12
|
+
import { z as z2 } from "zod";
|
|
13
|
+
|
|
14
|
+
// src/relay-credential-store.ts
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { platform } from "node:os";
|
|
17
|
+
import { brotliCompressSync, brotliDecompressSync } from "node:zlib";
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
var STORE_MESSAGES = {
|
|
20
|
+
unavailable: "Unlock your operating system credential store and restart AgentKnight. No file-based credential fallback is available.",
|
|
21
|
+
invalid: "The saved Relay credential is invalid. Recover it in your operating system credential manager before signing in.",
|
|
22
|
+
conflict: "A different Relay account or enrollment is already saved for this PC. Resolve it before signing in again.",
|
|
23
|
+
verification: "The operating system credential store did not retain the credential. Unlock it and restart AgentKnight.",
|
|
24
|
+
address: "Use an HTTPS Relay origin without a path, credentials, query, or fragment. HTTP is allowed only for literal loopback addresses.",
|
|
25
|
+
unsupported: "Microsoft sign-in requires Windows Credential Manager or macOS Keychain. This operating system is not supported.",
|
|
26
|
+
tooLarge: "The Relay credential exceeds the operating system credential store capacity. Existing credentials were not changed. Contact your Relay administrator."
|
|
27
|
+
};
|
|
28
|
+
var MAX_RECORD_BYTES = 32 * 1024;
|
|
29
|
+
var WINDOWS_MAX_SECRET_BYTES = 2560;
|
|
30
|
+
var COMPRESSED_RECORD_PREFIX = Buffer.from("AKR2\0");
|
|
31
|
+
var RelayCredentialStoreError = class extends Error {
|
|
32
|
+
constructor(code) {
|
|
33
|
+
super(STORE_MESSAGES[code]);
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.name = "RelayCredentialStoreError";
|
|
36
|
+
}
|
|
37
|
+
code;
|
|
38
|
+
};
|
|
39
|
+
function normalizeRelayOrigin(value) {
|
|
40
|
+
try {
|
|
41
|
+
const url = new URL(value);
|
|
42
|
+
const literalLoopback = /^http:\/\/(?:127\.0\.0\.1|\[::1\])(?::\d+)?\/?$/i.test(value);
|
|
43
|
+
if (!/^https?:\/\/[^/?#\\@\s]+\/?$/i.test(value) || url.username || url.password || url.search || url.hash || url.pathname !== "/" || url.protocol !== "https:" && !literalLoopback) {
|
|
44
|
+
throw new RelayCredentialStoreError("address");
|
|
45
|
+
}
|
|
46
|
+
return url.origin;
|
|
47
|
+
} catch {
|
|
48
|
+
throw new RelayCredentialStoreError("address");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
var ConfirmationSchema = z.discriminatedUnion("status", [
|
|
52
|
+
z.object({
|
|
53
|
+
status: z.literal("pending"),
|
|
54
|
+
confirmBy: z.number().int().positive(),
|
|
55
|
+
enrollmentId: PcEnrollmentIdSchema,
|
|
56
|
+
verifier: PcEnrollmentVerifierRequestSchema.shape.verifier
|
|
57
|
+
}).strict(),
|
|
58
|
+
z.object({
|
|
59
|
+
status: z.literal("confirmed"),
|
|
60
|
+
confirmBy: z.number().int().positive()
|
|
61
|
+
}).strict()
|
|
62
|
+
]);
|
|
63
|
+
var RelayCredentialSchema = z.object({
|
|
64
|
+
version: z.literal(1),
|
|
65
|
+
relayUrl: z.string().max(2048),
|
|
66
|
+
machineId: PcEnrollmentStartRequestSchema.shape.machineId,
|
|
67
|
+
token: z.string().min(32).max(4096),
|
|
68
|
+
tokenId: z.string().min(1).max(256),
|
|
69
|
+
grantId: z.uuid(),
|
|
70
|
+
user: AuthUserSchema,
|
|
71
|
+
confirmation: ConfirmationSchema
|
|
72
|
+
}).strict();
|
|
73
|
+
var SlotsSchema = z.object({
|
|
74
|
+
version: z.literal(1),
|
|
75
|
+
pending: RelayCredentialSchema.optional(),
|
|
76
|
+
confirmed: RelayCredentialSchema.optional()
|
|
77
|
+
}).strict();
|
|
78
|
+
function validateRelayCredentialSlots(value, relayUrl, machineId) {
|
|
79
|
+
const result = SlotsSchema.safeParse(value);
|
|
80
|
+
if (!result.success) throw new RelayCredentialStoreError("invalid");
|
|
81
|
+
const slots = result.data;
|
|
82
|
+
for (const slot of ["pending", "confirmed"]) {
|
|
83
|
+
const credential = slots[slot];
|
|
84
|
+
if (credential !== void 0 && (credential.relayUrl !== relayUrl || credential.machineId !== machineId || credential.confirmation.status !== slot || normalizeRelayOrigin(credential.relayUrl) !== credential.relayUrl)) throw new RelayCredentialStoreError("invalid");
|
|
85
|
+
}
|
|
86
|
+
if (slots.pending && slots.confirmed && slots.pending.user.userId !== slots.confirmed.user.userId) {
|
|
87
|
+
throw new RelayCredentialStoreError("conflict");
|
|
88
|
+
}
|
|
89
|
+
return slots;
|
|
90
|
+
}
|
|
91
|
+
function sameRelayCredential(left, right) {
|
|
92
|
+
const first = RelayCredentialSchema.safeParse(left);
|
|
93
|
+
const second = RelayCredentialSchema.safeParse(right);
|
|
94
|
+
if (!first.success || !second.success) throw new RelayCredentialStoreError("invalid");
|
|
95
|
+
return JSON.stringify(first.data) === JSON.stringify(second.data);
|
|
96
|
+
}
|
|
97
|
+
var transactions = /* @__PURE__ */ new Map();
|
|
98
|
+
var OsRelayCredentialStore = class {
|
|
99
|
+
constructor(entry, key, relayUrl, machineId, maxSecretBytes) {
|
|
100
|
+
this.entry = entry;
|
|
101
|
+
this.key = key;
|
|
102
|
+
this.relayUrl = relayUrl;
|
|
103
|
+
this.machineId = machineId;
|
|
104
|
+
this.maxSecretBytes = maxSecretBytes;
|
|
105
|
+
}
|
|
106
|
+
entry;
|
|
107
|
+
key;
|
|
108
|
+
relayUrl;
|
|
109
|
+
machineId;
|
|
110
|
+
maxSecretBytes;
|
|
111
|
+
async read() {
|
|
112
|
+
try {
|
|
113
|
+
const raw = await this.entry.getSecret();
|
|
114
|
+
if (raw == null) return { version: 1 };
|
|
115
|
+
const secret = raw instanceof Uint8Array ? Buffer.from(raw) : Array.isArray(raw) && raw.length <= MAX_RECORD_BYTES && raw.every((byte) => typeof byte === "number" && Number.isInteger(byte) && byte >= 0 && byte <= 255) ? Buffer.from(raw) : void 0;
|
|
116
|
+
if (secret === void 0 || secret.byteLength > MAX_RECORD_BYTES) throw new RelayCredentialStoreError("invalid");
|
|
117
|
+
let text;
|
|
118
|
+
if (secret.subarray(0, COMPRESSED_RECORD_PREFIX.length).equals(COMPRESSED_RECORD_PREFIX)) {
|
|
119
|
+
try {
|
|
120
|
+
text = brotliDecompressSync(secret.subarray(COMPRESSED_RECORD_PREFIX.length), {
|
|
121
|
+
maxOutputLength: MAX_RECORD_BYTES
|
|
122
|
+
}).toString("utf8");
|
|
123
|
+
} catch {
|
|
124
|
+
throw new RelayCredentialStoreError("invalid");
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
text = await this.entry.getPassword();
|
|
128
|
+
}
|
|
129
|
+
if (typeof text !== "string") throw new RelayCredentialStoreError("invalid");
|
|
130
|
+
if (Buffer.byteLength(text) > MAX_RECORD_BYTES) throw new RelayCredentialStoreError("invalid");
|
|
131
|
+
let value;
|
|
132
|
+
try {
|
|
133
|
+
value = JSON.parse(text);
|
|
134
|
+
} catch {
|
|
135
|
+
throw new RelayCredentialStoreError("invalid");
|
|
136
|
+
}
|
|
137
|
+
return validateRelayCredentialSlots(value, this.relayUrl, this.machineId);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
throw error instanceof RelayCredentialStoreError ? error : new RelayCredentialStoreError("unavailable");
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
savePending(credential) {
|
|
143
|
+
return this.transaction(async () => {
|
|
144
|
+
const candidate = validateRelayCredentialSlots(
|
|
145
|
+
{ version: 1, pending: credential },
|
|
146
|
+
this.relayUrl,
|
|
147
|
+
this.machineId
|
|
148
|
+
).pending;
|
|
149
|
+
if (candidate === void 0) throw new RelayCredentialStoreError("invalid");
|
|
150
|
+
const slots = await this.read();
|
|
151
|
+
if (slots.pending && !sameRelayCredential(slots.pending, candidate) || slots.confirmed && slots.confirmed.user.userId !== candidate.user.userId || slots.confirmed && slots.confirmed.tokenId === candidate.tokenId) throw new RelayCredentialStoreError("conflict");
|
|
152
|
+
await this.write({ ...slots, pending: candidate });
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
confirmPending(tokenId) {
|
|
156
|
+
return this.transaction(async () => {
|
|
157
|
+
const slots = await this.read();
|
|
158
|
+
const pending = slots.pending;
|
|
159
|
+
if (pending === void 0 || pending.tokenId !== tokenId) {
|
|
160
|
+
if (pending === void 0 && slots.confirmed?.tokenId === tokenId) return slots.confirmed;
|
|
161
|
+
throw new RelayCredentialStoreError("conflict");
|
|
162
|
+
}
|
|
163
|
+
const confirmed = {
|
|
164
|
+
...pending,
|
|
165
|
+
confirmation: { status: "confirmed", confirmBy: pending.confirmation.confirmBy }
|
|
166
|
+
};
|
|
167
|
+
await this.write({ version: 1, confirmed });
|
|
168
|
+
return confirmed;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
clearPending(tokenId) {
|
|
172
|
+
return this.transaction(async () => {
|
|
173
|
+
const slots = await this.read();
|
|
174
|
+
if (slots.pending === void 0) return;
|
|
175
|
+
if (slots.pending.tokenId !== tokenId) throw new RelayCredentialStoreError("conflict");
|
|
176
|
+
await this.write({
|
|
177
|
+
version: 1,
|
|
178
|
+
...slots.confirmed === void 0 ? {} : { confirmed: slots.confirmed }
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
async write(slots) {
|
|
183
|
+
const expected = validateRelayCredentialSlots(slots, this.relayUrl, this.machineId);
|
|
184
|
+
const json = Buffer.from(JSON.stringify(expected));
|
|
185
|
+
if (json.byteLength > MAX_RECORD_BYTES) throw new RelayCredentialStoreError("tooLarge");
|
|
186
|
+
const secret = Buffer.concat([COMPRESSED_RECORD_PREFIX, brotliCompressSync(json)]);
|
|
187
|
+
if (secret.byteLength > this.maxSecretBytes) throw new RelayCredentialStoreError("tooLarge");
|
|
188
|
+
await this.entry.setSecret(secret);
|
|
189
|
+
const actual = await this.read();
|
|
190
|
+
if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new RelayCredentialStoreError("verification");
|
|
191
|
+
}
|
|
192
|
+
async transaction(action) {
|
|
193
|
+
const previous = transactions.get(this.key) ?? Promise.resolve();
|
|
194
|
+
let release = () => {
|
|
195
|
+
};
|
|
196
|
+
const completion = new Promise((resolve) => {
|
|
197
|
+
release = resolve;
|
|
198
|
+
});
|
|
199
|
+
transactions.set(this.key, completion);
|
|
200
|
+
await previous;
|
|
201
|
+
try {
|
|
202
|
+
return await action();
|
|
203
|
+
} catch (error) {
|
|
204
|
+
throw error instanceof RelayCredentialStoreError ? error : new RelayCredentialStoreError("unavailable");
|
|
205
|
+
} finally {
|
|
206
|
+
release();
|
|
207
|
+
if (transactions.get(this.key) === completion) transactions.delete(this.key);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
async function createRelayCredentialStore(relayUrl, machineId) {
|
|
212
|
+
const os = platform();
|
|
213
|
+
if (os !== "win32" && os !== "darwin") throw new RelayCredentialStoreError("unsupported");
|
|
214
|
+
const origin = normalizeRelayOrigin(relayUrl);
|
|
215
|
+
if (!PcEnrollmentStartRequestSchema.shape.machineId.safeParse(machineId).success) {
|
|
216
|
+
throw new RelayCredentialStoreError("invalid");
|
|
217
|
+
}
|
|
218
|
+
const username = createHash("sha256").update(JSON.stringify([origin, machineId])).digest("hex");
|
|
219
|
+
try {
|
|
220
|
+
const { AsyncEntry } = await import("@napi-rs/keyring");
|
|
221
|
+
const entry = new AsyncEntry("AgentKnight Relay", username);
|
|
222
|
+
return new OsRelayCredentialStore(
|
|
223
|
+
entry,
|
|
224
|
+
username,
|
|
225
|
+
origin,
|
|
226
|
+
machineId,
|
|
227
|
+
os === "win32" ? WINDOWS_MAX_SECRET_BYTES : MAX_RECORD_BYTES
|
|
228
|
+
);
|
|
229
|
+
} catch {
|
|
230
|
+
throw new RelayCredentialStoreError("unavailable");
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// src/aad-relay-login.ts
|
|
235
|
+
var AadLoginError = class extends Error {
|
|
236
|
+
};
|
|
237
|
+
function safeFailure(error) {
|
|
238
|
+
if (error instanceof AadLoginError) return error;
|
|
239
|
+
const code = z2.object({ errorCode: z2.string().regex(/^[a-z0-9_]{1,80}$/u) }).safeParse(error);
|
|
240
|
+
return new AadLoginError(`AAD sign-in failed${code.success ? ` (${code.data.errorCode})` : ""}. Check the OS account, network and Relay access policy, then sign in again.`);
|
|
241
|
+
}
|
|
242
|
+
async function readAadAccount(relayUrl, token, fetch = globalThis.fetch) {
|
|
243
|
+
const origin = normalizeRelayOrigin(relayUrl);
|
|
244
|
+
if (!origin.startsWith("https:") || process.env.NODE_TLS_REJECT_UNAUTHORIZED === "0") {
|
|
245
|
+
throw new AadLoginError("AAD requires HTTPS with certificate verification.");
|
|
246
|
+
}
|
|
247
|
+
const response = await fetch(`${origin}/auth/aad/me`, {
|
|
248
|
+
headers: { authorization: `Bearer ${token}`, accept: "application/json" },
|
|
249
|
+
redirect: "error",
|
|
250
|
+
credentials: "omit",
|
|
251
|
+
cache: "no-store",
|
|
252
|
+
signal: AbortSignal.timeout(1e4)
|
|
253
|
+
});
|
|
254
|
+
const reader = response.body?.getReader();
|
|
255
|
+
try {
|
|
256
|
+
if (!response.ok || response.redirected || reader === void 0) {
|
|
257
|
+
throw new AadLoginError(`Relay AAD admission failed (HTTP ${response.status}). Check the configured application and access group.`);
|
|
258
|
+
}
|
|
259
|
+
const chunks = [];
|
|
260
|
+
let size = 0;
|
|
261
|
+
for (; ; ) {
|
|
262
|
+
const chunk = await reader.read();
|
|
263
|
+
if (chunk.done) break;
|
|
264
|
+
size += chunk.value.byteLength;
|
|
265
|
+
if (size > 16384) throw new AadLoginError("Relay returned an invalid AAD account response.");
|
|
266
|
+
chunks.push(chunk.value);
|
|
267
|
+
}
|
|
268
|
+
return AadAccountResultSchema.parse(JSON.parse(Buffer.concat(chunks).toString("utf8"))).user;
|
|
269
|
+
} finally {
|
|
270
|
+
await reader?.cancel();
|
|
271
|
+
reader?.releaseLock();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
var AadRelayLogin = class {
|
|
275
|
+
constructor(options) {
|
|
276
|
+
this.options = options;
|
|
277
|
+
this.relayOrigin = normalizeRelayOrigin(options.relayUrl);
|
|
278
|
+
for (const id of [options.tenantId, options.clientId, options.apiClientId]) z2.uuid().parse(id);
|
|
279
|
+
if (!this.relayOrigin.startsWith("https:") || options.clientId === options.apiClientId) {
|
|
280
|
+
throw new AadLoginError("AAD requires an HTTPS origin and independent native/API applications.");
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
options;
|
|
284
|
+
method = "aad";
|
|
285
|
+
relayOrigin;
|
|
286
|
+
#state = { state: "signed-out" };
|
|
287
|
+
#account;
|
|
288
|
+
#credential;
|
|
289
|
+
#expiresAt = 0;
|
|
290
|
+
#generation = 0;
|
|
291
|
+
#closed = false;
|
|
292
|
+
#active;
|
|
293
|
+
#refresh;
|
|
294
|
+
#waiters = /* @__PURE__ */ new Set();
|
|
295
|
+
getState() {
|
|
296
|
+
return { ...this.#state };
|
|
297
|
+
}
|
|
298
|
+
acceptCallback() {
|
|
299
|
+
return void 0;
|
|
300
|
+
}
|
|
301
|
+
async restore() {
|
|
302
|
+
const generation = this.#generation;
|
|
303
|
+
try {
|
|
304
|
+
const selected = await this.options.store.read();
|
|
305
|
+
if (selected === void 0 || this.#closed || generation !== this.#generation) return void 0;
|
|
306
|
+
const accounts = await this.options.client.getAllAccounts();
|
|
307
|
+
if (this.#closed || generation !== this.#generation) return void 0;
|
|
308
|
+
this.#account = accounts.find((account) => account.homeAccountId === selected && account.tenantId.toLowerCase() === this.options.tenantId);
|
|
309
|
+
if (this.#account === void 0) throw new AadLoginError("The saved OS account is unavailable. Sign in again.");
|
|
310
|
+
await this.#acquire(false, generation);
|
|
311
|
+
return this.#credential;
|
|
312
|
+
} catch (error) {
|
|
313
|
+
if (!this.#closed && generation === this.#generation) {
|
|
314
|
+
this.#state = { state: "error", message: safeFailure(error).message };
|
|
315
|
+
}
|
|
316
|
+
return void 0;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
async start() {
|
|
320
|
+
if (this.#closed) throw new AadLoginError("AAD sign-in is closed.");
|
|
321
|
+
if (this.#active !== void 0 || this.#state.state === "signed-in") return;
|
|
322
|
+
this.#state = { state: "starting" };
|
|
323
|
+
const generation = this.#generation;
|
|
324
|
+
this.#active = this.#acquire(true, generation).then(() => void 0, (error) => {
|
|
325
|
+
if (!this.#closed && generation === this.#generation) this.#state = { state: "error", message: safeFailure(error).message };
|
|
326
|
+
}).finally(() => {
|
|
327
|
+
this.#active = void 0;
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
async cancel() {
|
|
331
|
+
this.#generation++;
|
|
332
|
+
this.#credential = void 0;
|
|
333
|
+
this.#account = void 0;
|
|
334
|
+
this.#expiresAt = 0;
|
|
335
|
+
this.#state = { state: "signed-out" };
|
|
336
|
+
}
|
|
337
|
+
async close() {
|
|
338
|
+
this.#closed = true;
|
|
339
|
+
this.#generation++;
|
|
340
|
+
this.#credential = void 0;
|
|
341
|
+
this.#account = void 0;
|
|
342
|
+
for (const waiter of this.#waiters) waiter.reject(new AadLoginError("AAD sign-in cancelled."));
|
|
343
|
+
this.#waiters.clear();
|
|
344
|
+
}
|
|
345
|
+
waitForCredential(signal) {
|
|
346
|
+
if (this.#closed || signal?.aborted) return Promise.reject(new AadLoginError("AAD sign-in cancelled."));
|
|
347
|
+
if (this.#state.state === "signed-in" && this.#credential !== void 0) return Promise.resolve(this.#credential);
|
|
348
|
+
return new Promise((resolve, reject) => {
|
|
349
|
+
const cleanup = () => {
|
|
350
|
+
signal?.removeEventListener("abort", abort);
|
|
351
|
+
this.#waiters.delete(waiter);
|
|
352
|
+
};
|
|
353
|
+
const waiter = {
|
|
354
|
+
resolve: (value) => {
|
|
355
|
+
cleanup();
|
|
356
|
+
resolve(value);
|
|
357
|
+
},
|
|
358
|
+
reject: (error) => {
|
|
359
|
+
cleanup();
|
|
360
|
+
reject(error);
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
const abort = () => waiter.reject(new AadLoginError("AAD sign-in cancelled."));
|
|
364
|
+
this.#waiters.add(waiter);
|
|
365
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
async getAccessToken() {
|
|
369
|
+
if (this.#closed || this.#account === void 0) throw new AadLoginError("AAD account is unavailable. Sign in again.");
|
|
370
|
+
if (this.#state.state === "signed-in" && this.#credential !== void 0 && this.#expiresAt > Date.now() + 12e4) {
|
|
371
|
+
return { token: this.#credential.token, expiresAt: this.#expiresAt };
|
|
372
|
+
}
|
|
373
|
+
this.#refresh ??= this.#acquire(false, this.#generation).finally(() => {
|
|
374
|
+
this.#refresh = void 0;
|
|
375
|
+
});
|
|
376
|
+
return this.#refresh;
|
|
377
|
+
}
|
|
378
|
+
async #acquire(interactive, generation) {
|
|
379
|
+
try {
|
|
380
|
+
const scopes = [`api://${this.options.apiClientId}/relay.host`];
|
|
381
|
+
const previous = this.#account;
|
|
382
|
+
const result = interactive ? await this.options.client.acquireTokenInteractive({
|
|
383
|
+
scopes,
|
|
384
|
+
prompt: "select_account",
|
|
385
|
+
openBrowser: async () => {
|
|
386
|
+
throw new AadLoginError("The OS broker is required; browser fallback is disabled.");
|
|
387
|
+
}
|
|
388
|
+
}) : previous === void 0 ? void 0 : await this.options.client.acquireTokenSilent({ scopes, account: previous });
|
|
389
|
+
if (this.#closed || generation !== this.#generation) throw new AadLoginError("AAD sign-in cancelled.");
|
|
390
|
+
const claims = z2.object({ tid: z2.uuid(), oid: z2.uuid(), aud: z2.uuid() }).safeParse(result?.idTokenClaims);
|
|
391
|
+
const expiresAt = result?.expiresOn?.getTime() ?? 0;
|
|
392
|
+
if (result === void 0 || result.account === null || !claims.success || result.fromPlatformBroker !== true || result.tokenType.toLowerCase() !== "bearer" || claims.data.tid.toLowerCase() !== this.options.tenantId || result.tenantId.toLowerCase() !== this.options.tenantId || claims.data.aud.toLowerCase() !== this.options.clientId || !result.scopes.includes(scopes[0] ?? "") || expiresAt <= Date.now() + 5e3 || !/^[\x21-\x7e]{1,32768}$/u.test(result.accessToken)) {
|
|
393
|
+
throw new AadLoginError("AAD broker returned an invalid identity, scope or token lifetime.");
|
|
394
|
+
}
|
|
395
|
+
const userId = `aad:${this.options.tenantId}:${claims.data.oid.toLowerCase()}`;
|
|
396
|
+
if (!interactive && (result.account.homeAccountId !== previous?.homeAccountId || this.#credential !== void 0 && this.#credential.user.userId !== userId)) {
|
|
397
|
+
throw new AadLoginError("AAD account identity changed. Sign in again.");
|
|
398
|
+
}
|
|
399
|
+
const user = await readAadAccount(this.relayOrigin, result.accessToken, this.options.fetch);
|
|
400
|
+
if (user.userId !== userId) throw new AadLoginError("Relay returned a different AAD account identity.");
|
|
401
|
+
if (this.#closed || generation !== this.#generation) throw new AadLoginError("AAD sign-in cancelled.");
|
|
402
|
+
await this.options.store.save(result.account.homeAccountId);
|
|
403
|
+
if (this.#closed || generation !== this.#generation) throw new AadLoginError("AAD sign-in cancelled.");
|
|
404
|
+
this.#account = result.account;
|
|
405
|
+
this.#expiresAt = expiresAt;
|
|
406
|
+
this.#credential = { token: result.accessToken, user, relayAuthorization: this, close: () => this.close() };
|
|
407
|
+
this.#state = { state: "signed-in", userId };
|
|
408
|
+
for (const waiter of this.#waiters) waiter.resolve(this.#credential);
|
|
409
|
+
this.#waiters.clear();
|
|
410
|
+
return { token: result.accessToken, expiresAt };
|
|
411
|
+
} catch (error) {
|
|
412
|
+
const failure = safeFailure(error);
|
|
413
|
+
if (!this.#closed && generation === this.#generation) {
|
|
414
|
+
this.#state = { state: "error", message: failure.message };
|
|
415
|
+
}
|
|
416
|
+
throw failure;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
async function createAadAccountStore(options) {
|
|
421
|
+
const { AsyncEntry } = await import("@napi-rs/keyring");
|
|
422
|
+
const key = createHash2("sha256").update(JSON.stringify([
|
|
423
|
+
normalizeRelayOrigin(options.relayUrl),
|
|
424
|
+
options.tenantId,
|
|
425
|
+
options.clientId,
|
|
426
|
+
options.apiClientId,
|
|
427
|
+
options.machineId
|
|
428
|
+
])).digest("hex");
|
|
429
|
+
const entry = new AsyncEntry("AgentKnight AAD account", key);
|
|
430
|
+
return {
|
|
431
|
+
read: async () => {
|
|
432
|
+
const value = await entry.getPassword();
|
|
433
|
+
return value == null ? void 0 : z2.string().min(1).max(512).parse(value);
|
|
434
|
+
},
|
|
435
|
+
save: async (value) => {
|
|
436
|
+
z2.string().min(1).max(512).parse(value);
|
|
437
|
+
await entry.setPassword(value);
|
|
438
|
+
if (await entry.getPassword() !== value) throw new AadLoginError("The OS credential store did not retain the selected account.");
|
|
439
|
+
},
|
|
440
|
+
remove: async () => {
|
|
441
|
+
await entry.deletePassword();
|
|
442
|
+
if (await entry.getPassword() != null) throw new AadLoginError("The OS credential store did not remove the selected account.");
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
async function createAadRelayLogin(options) {
|
|
447
|
+
try {
|
|
448
|
+
const [{ PublicClientApplication }, { NativeBrokerPlugin }] = await Promise.all([
|
|
449
|
+
import("@azure/msal-node"),
|
|
450
|
+
import("@azure/msal-node-extensions")
|
|
451
|
+
]);
|
|
452
|
+
const broker = new NativeBrokerPlugin();
|
|
453
|
+
if (!broker.isBrokerAvailable) throw new AadLoginError("The OS authentication broker is unavailable. Repair OS sign-in support; no fallback was attempted.");
|
|
454
|
+
const client = new PublicClientApplication({
|
|
455
|
+
auth: { clientId: options.clientId, authority: `https://login.microsoftonline.com/${options.tenantId}` },
|
|
456
|
+
broker: { nativeBrokerPlugin: broker }
|
|
457
|
+
});
|
|
458
|
+
const store = await createAadAccountStore(options);
|
|
459
|
+
return new AadRelayLogin({ ...options, client, store });
|
|
460
|
+
} catch (error) {
|
|
461
|
+
throw safeFailure(error);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export {
|
|
466
|
+
RelayCredentialStoreError,
|
|
467
|
+
normalizeRelayOrigin,
|
|
468
|
+
validateRelayCredentialSlots,
|
|
469
|
+
sameRelayCredential,
|
|
470
|
+
createRelayCredentialStore,
|
|
471
|
+
readAadAccount,
|
|
472
|
+
AadRelayLogin,
|
|
473
|
+
createAadAccountStore,
|
|
474
|
+
createAadRelayLogin
|
|
475
|
+
};
|