@primitive.ai/prim 0.1.0-alpha.123 → 0.1.0-alpha.125
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/README.md +90 -0
- package/dist/{chunk-RUEIVZ6T.js → chunk-2BEUR3DU.js} +2 -2
- package/dist/{chunk-5ME3WD3P.js → chunk-6KXQQ7CQ.js} +6 -3
- package/dist/{chunk-CWV5ZQR6.js → chunk-6OPSSJHO.js} +5 -5
- package/dist/{chunk-4NUGCUQC.js → chunk-74DQDWLW.js} +2 -2
- package/dist/{chunk-WN7OURQ3.js → chunk-BFYJLI7V.js} +1 -1
- package/dist/{chunk-T2T45KF6.js → chunk-DT7E3SD5.js} +4 -4
- package/dist/{chunk-DQ4I3FLF.js → chunk-EZXIKEMA.js} +3 -3
- package/dist/{chunk-4M23K2KZ.js → chunk-FYYHBOOM.js} +2 -2
- package/dist/{chunk-3WQ7SBOZ.js → chunk-HPA7RGSZ.js} +3 -3
- package/dist/{chunk-NL5VU7EU.js → chunk-JFWJN2ME.js} +3 -3
- package/dist/{chunk-GOMEWFMG.js → chunk-L32WYFJT.js} +143 -61
- package/dist/{chunk-OXW6PSPT.js → chunk-NBNQI3YJ.js} +15 -3
- package/dist/{chunk-LOFMI3D4.js → chunk-ND6TYHNI.js} +2 -2
- package/dist/{chunk-4GYJHN26.js → chunk-NJBN3WXF.js} +1607 -549
- package/dist/{chunk-HLMC7VS4.js → chunk-O73J3KQQ.js} +5702 -2860
- package/dist/{chunk-JZC2LHS6.js → chunk-PPZ56EVJ.js} +1 -1
- package/dist/{chunk-FXXMDO7D.js → chunk-R35M4RCY.js} +4 -4
- package/dist/chunk-TI37ME2D.js +210 -0
- package/dist/{chunk-NMZSCSMY.js → chunk-YP4OXKNX.js} +13 -1
- package/dist/{chunk-S3ZIMGXV.js → chunk-ZKXNJB6U.js} +76 -2
- package/dist/daemon/server.js +12321 -8354
- package/dist/hook-runtime/daemon/server.js +12321 -8354
- package/dist/hook-runtime/hooks/post-commit.js +6743 -3634
- package/dist/hook-runtime/hooks/post-rewrite.js +6776 -3668
- package/dist/hook-runtime/hooks/post-tool-use.js +7108 -3140
- package/dist/hook-runtime/hooks/pre-commit.js +1263 -280
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +15115 -11297
- package/dist/hook-runtime/hooks/prim-hook.js +10879 -7024
- package/dist/hook-runtime/hooks/session-end.js +399 -139
- package/dist/hook-runtime/hooks/session-start.js +13277 -9454
- package/dist/hook-runtime/index.js +17575 -13050
- package/dist/hook-runtime/statusline-main.js +375 -122
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +31 -21
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +16 -12
- package/dist/index.js +9124 -8763
- package/dist/statusline-main.js +375 -122
- package/package.json +3 -1
- package/dist/chunk-RRAC76LJ.js +0 -36
|
@@ -82,9 +82,9 @@ function publicDecisionResponse(value) {
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
// src/client.ts
|
|
85
|
-
import { createHash as
|
|
86
|
-
import { chmodSync as
|
|
87
|
-
import { dirname as
|
|
85
|
+
import { createHash as createHash5 } from "crypto";
|
|
86
|
+
import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
|
|
87
|
+
import { dirname as dirname5 } from "path";
|
|
88
88
|
|
|
89
89
|
// src/lib/atomic-file.ts
|
|
90
90
|
import { randomUUID } from "crypto";
|
|
@@ -102,6 +102,7 @@ import {
|
|
|
102
102
|
import { dirname } from "path";
|
|
103
103
|
var DEFAULT_FILE_MODE = 438;
|
|
104
104
|
function syncDirectory(path) {
|
|
105
|
+
if (process.platform === "win32") return;
|
|
105
106
|
const fd = openSync(path, constants.O_RDONLY);
|
|
106
107
|
try {
|
|
107
108
|
fsyncSync(fd);
|
|
@@ -165,37 +166,220 @@ function atomicWriteFile(target, content, options = {}) {
|
|
|
165
166
|
}
|
|
166
167
|
|
|
167
168
|
// src/lib/credentials.ts
|
|
168
|
-
import { createHash } from "crypto";
|
|
169
|
-
import { readFileSync } from "fs";
|
|
170
|
-
import { join as
|
|
169
|
+
import { createHash as createHash4 } from "crypto";
|
|
170
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
171
|
+
import { join as join7 } from "path";
|
|
171
172
|
|
|
172
|
-
// src/lib/
|
|
173
|
-
import {
|
|
174
|
-
import {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
173
|
+
// src/lib/machine-credentials.ts
|
|
174
|
+
import { execFileSync } from "child_process";
|
|
175
|
+
import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
|
|
176
|
+
import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
|
|
177
|
+
import { createRequire } from "module";
|
|
178
|
+
import { dirname as dirname4, join as join6 } from "path";
|
|
179
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
180
|
+
|
|
181
|
+
// src/lib/file-lock.ts
|
|
182
|
+
import { randomBytes } from "crypto";
|
|
183
|
+
import { existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
184
|
+
import { dirname as dirname2, join } from "path";
|
|
185
|
+
|
|
186
|
+
// src/lib/process-liveness.ts
|
|
187
|
+
function processIsAlive(pid, probe = process.kill) {
|
|
188
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
189
|
+
try {
|
|
190
|
+
probe(pid, 0);
|
|
191
|
+
return true;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
return error.code === "EPERM";
|
|
179
194
|
}
|
|
180
|
-
if (!value || value.trim() !== value || !isAbsolute(value)) return;
|
|
181
|
-
const normalized = normalize(value);
|
|
182
|
-
return normalized === value ? value : void 0;
|
|
183
195
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
196
|
+
|
|
197
|
+
// src/lib/file-lock.ts
|
|
198
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
199
|
+
var DEFAULT_POLL_MS = 50;
|
|
200
|
+
var DEFAULT_INIT_GRACE_MS = 2e3;
|
|
201
|
+
var DIRECTORY_MODE = 448;
|
|
202
|
+
var FILE_MODE = 384;
|
|
203
|
+
function ownerPath(lockDir) {
|
|
204
|
+
return join(lockDir, "owner.json");
|
|
205
|
+
}
|
|
206
|
+
function readOwner(lockDir) {
|
|
207
|
+
try {
|
|
208
|
+
const owner = JSON.parse(readFileSync(ownerPath(lockDir), "utf8"));
|
|
209
|
+
if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
return owner;
|
|
213
|
+
} catch {
|
|
214
|
+
return null;
|
|
193
215
|
}
|
|
194
|
-
return { path: join(home, ".config", "prim"), source: "default" };
|
|
195
216
|
}
|
|
196
|
-
function
|
|
197
|
-
return
|
|
217
|
+
function sameOwner(a, b) {
|
|
218
|
+
return a?.pid === b.pid && a.nonce === b.nonce && a.createdAt === b.createdAt;
|
|
219
|
+
}
|
|
220
|
+
function tryTakeLock(lockDir, now) {
|
|
221
|
+
try {
|
|
222
|
+
mkdirSync2(lockDir, { mode: DIRECTORY_MODE });
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if (error.code === "EEXIST") return null;
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
const owner = {
|
|
228
|
+
pid: process.pid,
|
|
229
|
+
nonce: randomBytes(16).toString("hex"),
|
|
230
|
+
createdAt: now
|
|
231
|
+
};
|
|
232
|
+
try {
|
|
233
|
+
writeFileSync2(ownerPath(lockDir), `${JSON.stringify(owner)}
|
|
234
|
+
`, {
|
|
235
|
+
encoding: "utf8",
|
|
236
|
+
mode: FILE_MODE,
|
|
237
|
+
flag: "wx"
|
|
238
|
+
});
|
|
239
|
+
return owner;
|
|
240
|
+
} catch (error) {
|
|
241
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
242
|
+
throw error;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function recoverStaleLock(lockDir, now, alive, initGraceMs) {
|
|
246
|
+
const owner = readOwner(lockDir);
|
|
247
|
+
if (owner) {
|
|
248
|
+
if (alive(owner.pid)) return false;
|
|
249
|
+
if (!sameOwner(readOwner(lockDir), owner)) return false;
|
|
250
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
try {
|
|
254
|
+
const before = statSync(lockDir).mtimeMs;
|
|
255
|
+
if (now - before < initGraceMs) return false;
|
|
256
|
+
if (readOwner(lockDir)) return false;
|
|
257
|
+
if (statSync(lockDir).mtimeMs !== before) return false;
|
|
258
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
259
|
+
return true;
|
|
260
|
+
} catch {
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function abortError(signal) {
|
|
265
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
266
|
+
const error = new Error("The operation was aborted");
|
|
267
|
+
error.name = "AbortError";
|
|
268
|
+
return error;
|
|
269
|
+
}
|
|
270
|
+
function throwIfAborted(signal) {
|
|
271
|
+
if (signal?.aborted) throw abortError(signal);
|
|
198
272
|
}
|
|
273
|
+
async function defaultSleep(ms, signal) {
|
|
274
|
+
if (!signal) {
|
|
275
|
+
await new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
throwIfAborted(signal);
|
|
279
|
+
await new Promise((resolve3, reject) => {
|
|
280
|
+
const timer = setTimeout(() => {
|
|
281
|
+
signal.removeEventListener("abort", onAbort);
|
|
282
|
+
resolve3();
|
|
283
|
+
}, ms);
|
|
284
|
+
const onAbort = () => {
|
|
285
|
+
clearTimeout(timer);
|
|
286
|
+
reject(abortError(signal));
|
|
287
|
+
};
|
|
288
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
292
|
+
async function withFileLock(lockDir, operation, options = {}) {
|
|
293
|
+
mkdirSync2(dirname2(lockDir), { recursive: true, mode: DIRECTORY_MODE });
|
|
294
|
+
const nowMs = options.nowMs ?? Date.now;
|
|
295
|
+
const alive = options.processAlive ?? processIsAlive;
|
|
296
|
+
const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
297
|
+
let owner = null;
|
|
298
|
+
while (!owner) {
|
|
299
|
+
throwIfAborted(options.signal);
|
|
300
|
+
const now = nowMs();
|
|
301
|
+
owner = tryTakeLock(lockDir, now);
|
|
302
|
+
if (owner) break;
|
|
303
|
+
recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
|
|
304
|
+
if (now >= deadline) {
|
|
305
|
+
throw new Error(`timed out waiting for file lock ${lockDir}`);
|
|
306
|
+
}
|
|
307
|
+
if (options.sleep) {
|
|
308
|
+
await options.sleep(options.pollMs ?? DEFAULT_POLL_MS);
|
|
309
|
+
throwIfAborted(options.signal);
|
|
310
|
+
} else {
|
|
311
|
+
await defaultSleep(options.pollMs ?? DEFAULT_POLL_MS, options.signal);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
throwIfAborted(options.signal);
|
|
316
|
+
return await operation();
|
|
317
|
+
} finally {
|
|
318
|
+
if (sameOwner(readOwner(lockDir), owner)) {
|
|
319
|
+
rmSync2(lockDir, { recursive: true, force: true });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// src/lib/machine-broker.ts
|
|
325
|
+
import { spawn } from "child_process";
|
|
326
|
+
import { createHash, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
327
|
+
import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
|
|
328
|
+
import { createServer } from "http";
|
|
329
|
+
import { basename, join as join4 } from "path";
|
|
330
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
331
|
+
|
|
332
|
+
// src/lib/bin-path.ts
|
|
333
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
334
|
+
import { dirname as dirname3, isAbsolute, join as join2 } from "path";
|
|
335
|
+
import { fileURLToPath } from "url";
|
|
336
|
+
var PKG_NAME = "@primitive.ai/prim";
|
|
337
|
+
var ROOT_WALK_LIMIT = 6;
|
|
338
|
+
var resolvedRoot;
|
|
339
|
+
function locateRoot() {
|
|
340
|
+
if (resolvedRoot !== void 0) {
|
|
341
|
+
return resolvedRoot;
|
|
342
|
+
}
|
|
343
|
+
let dir = dirname3(fileURLToPath(import.meta.url));
|
|
344
|
+
for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
|
|
345
|
+
const manifestPath = join2(dir, "package.json");
|
|
346
|
+
if (existsSync2(manifestPath)) {
|
|
347
|
+
try {
|
|
348
|
+
const manifest = JSON.parse(readFileSync2(manifestPath, "utf-8"));
|
|
349
|
+
if (manifest.name === PKG_NAME && manifest.bin) {
|
|
350
|
+
resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
|
|
351
|
+
return resolvedRoot;
|
|
352
|
+
}
|
|
353
|
+
} catch {
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const parent = dirname3(dir);
|
|
357
|
+
if (parent === dir) {
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
dir = parent;
|
|
361
|
+
}
|
|
362
|
+
resolvedRoot = null;
|
|
363
|
+
return resolvedRoot;
|
|
364
|
+
}
|
|
365
|
+
function binFile(bin) {
|
|
366
|
+
const root = locateRoot();
|
|
367
|
+
const rel = root?.bin[bin];
|
|
368
|
+
if (!root || !rel) {
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
return isAbsolute(rel) ? rel : join2(root.dir, rel);
|
|
372
|
+
}
|
|
373
|
+
function packageVersion() {
|
|
374
|
+
return locateRoot()?.version ?? null;
|
|
375
|
+
}
|
|
376
|
+
var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
377
|
+
'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
|
|
378
|
+
'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
|
|
379
|
+
'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
|
|
380
|
+
'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
|
|
381
|
+
"fi; fi; "
|
|
382
|
+
].join("");
|
|
199
383
|
|
|
200
384
|
// src/lib/workos-connect.ts
|
|
201
385
|
var TOKEN_PATH = "/oauth2/token";
|
|
@@ -326,43 +510,933 @@ async function readBoundedJson(response, maxBytes) {
|
|
|
326
510
|
function workosConnectTokenEndpoint(issuer) {
|
|
327
511
|
return `${issuer}${TOKEN_PATH}`;
|
|
328
512
|
}
|
|
329
|
-
function parseWorkosConnectTokens(value, options = {}) {
|
|
330
|
-
const record = recordFrom(value, "token response");
|
|
331
|
-
const accessToken = exactString(
|
|
332
|
-
record.access_token,
|
|
333
|
-
"access_token",
|
|
334
|
-
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
513
|
+
function parseWorkosConnectTokens(value, options = {}) {
|
|
514
|
+
const record = recordFrom(value, "token response");
|
|
515
|
+
const accessToken = exactString(
|
|
516
|
+
record.access_token,
|
|
517
|
+
"access_token",
|
|
518
|
+
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
519
|
+
);
|
|
520
|
+
const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
521
|
+
return {
|
|
522
|
+
accessToken,
|
|
523
|
+
refreshToken: refreshToken2,
|
|
524
|
+
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// src/lib/machine-protocol.ts
|
|
529
|
+
var MachineAuthError = class extends Error {
|
|
530
|
+
constructor(code, message, terminal = false, retryAt) {
|
|
531
|
+
super(message);
|
|
532
|
+
this.code = code;
|
|
533
|
+
this.terminal = terminal;
|
|
534
|
+
this.retryAt = retryAt;
|
|
535
|
+
this.name = "MachineAuthError";
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
function machineRetryAt(response, now = Date.now()) {
|
|
539
|
+
const value = response.headers.get("Retry-After")?.trim();
|
|
540
|
+
if (!value || value.length > 128) return void 0;
|
|
541
|
+
const timestamp = /^\d+$/u.test(value) ? now + Number(value) * 1e3 : Date.parse(value);
|
|
542
|
+
return Number.isSafeInteger(timestamp) && timestamp > now ? timestamp : void 0;
|
|
543
|
+
}
|
|
544
|
+
function machineString(value, maximum = 4096) {
|
|
545
|
+
return typeof value === "string" && value.length > 0 && value.length <= maximum && value.trim() === value && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
546
|
+
}
|
|
547
|
+
function machineRecord(value) {
|
|
548
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
549
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
550
|
+
}
|
|
551
|
+
return value;
|
|
552
|
+
}
|
|
553
|
+
function machineApiUrl(value) {
|
|
554
|
+
const url = new URL(value);
|
|
555
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
556
|
+
if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
557
|
+
throw new MachineAuthError("invalid_configuration", "The API URL must be an HTTPS origin.");
|
|
558
|
+
}
|
|
559
|
+
return url.origin;
|
|
560
|
+
}
|
|
561
|
+
function parseMachineConfiguration(value) {
|
|
562
|
+
const record = machineRecord(value);
|
|
563
|
+
if (record.protocol_version !== 1 || !machineString(record.issuer, 2048) || !machineString(record.audience, 256) || !/^client_[\w-]+$/u.test(record.audience)) {
|
|
564
|
+
throw new MachineAuthError("invalid_configuration", "Invalid M2M discovery configuration.");
|
|
565
|
+
}
|
|
566
|
+
const issuer = new URL(record.issuer);
|
|
567
|
+
if (issuer.protocol !== "https:" || issuer.origin !== record.issuer) {
|
|
568
|
+
throw new MachineAuthError(
|
|
569
|
+
"invalid_configuration",
|
|
570
|
+
"The WorkOS issuer must be an HTTPS origin."
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
issuer: record.issuer,
|
|
575
|
+
audience: record.audience,
|
|
576
|
+
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
function machineSignal(signal) {
|
|
580
|
+
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
581
|
+
}
|
|
582
|
+
async function fetchMachine(url, options, fetchImpl) {
|
|
583
|
+
try {
|
|
584
|
+
return await fetchImpl(url, options);
|
|
585
|
+
} catch {
|
|
586
|
+
options.signal?.throwIfAborted();
|
|
587
|
+
throw new MachineAuthError(
|
|
588
|
+
"authentication_unavailable",
|
|
589
|
+
"Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
async function readMachineJson(response, maximumBytes) {
|
|
594
|
+
try {
|
|
595
|
+
return await readBoundedJson(response, maximumBytes);
|
|
596
|
+
} catch {
|
|
597
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
601
|
+
const response = await fetchMachine(
|
|
602
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/m2m/config`,
|
|
603
|
+
{
|
|
604
|
+
signal: machineSignal(signal),
|
|
605
|
+
redirect: "error"
|
|
606
|
+
},
|
|
607
|
+
fetchImpl
|
|
608
|
+
);
|
|
609
|
+
if (!response.ok)
|
|
610
|
+
throw new MachineAuthError(
|
|
611
|
+
response.status === 404 ? "server_upgrade_required" : "discovery_unavailable",
|
|
612
|
+
response.status === 404 ? "This server does not support machine authentication yet." : "Machine authentication discovery is unavailable."
|
|
613
|
+
);
|
|
614
|
+
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
615
|
+
}
|
|
616
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
617
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
618
|
+
throw new MachineAuthError(
|
|
619
|
+
"invalid_credentials",
|
|
620
|
+
"A machine client ID and secret are required.",
|
|
621
|
+
true
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
const response = await fetchMachine(
|
|
625
|
+
`${configuration.issuer}/oauth2/token`,
|
|
626
|
+
{
|
|
627
|
+
method: "POST",
|
|
628
|
+
redirect: "error",
|
|
629
|
+
signal: machineSignal(signal),
|
|
630
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
631
|
+
body: new URLSearchParams({
|
|
632
|
+
grant_type: "client_credentials",
|
|
633
|
+
client_id: clientId,
|
|
634
|
+
client_secret: clientSecret
|
|
635
|
+
})
|
|
636
|
+
},
|
|
637
|
+
fetchImpl
|
|
638
|
+
);
|
|
639
|
+
if (!response.ok) {
|
|
640
|
+
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
641
|
+
throw new MachineAuthError(
|
|
642
|
+
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
643
|
+
terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
|
|
644
|
+
terminal,
|
|
645
|
+
terminal ? void 0 : machineRetryAt(response)
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
const data = machineRecord(await readMachineJson(response, 64 * 1024));
|
|
649
|
+
if (!machineString(data.access_token, 60 * 1024) || typeof data.token_type !== "string" || data.token_type.toLowerCase() !== "bearer" || !Number.isSafeInteger(data.expires_in) || data.expires_in <= 0 || data.expires_in > 86400) {
|
|
650
|
+
throw new MachineAuthError(
|
|
651
|
+
"invalid_response",
|
|
652
|
+
"The token service returned an invalid access token."
|
|
653
|
+
);
|
|
654
|
+
}
|
|
655
|
+
let claims;
|
|
656
|
+
try {
|
|
657
|
+
claims = machineRecord(
|
|
658
|
+
JSON.parse(Buffer.from(data.access_token.split(".")[1] ?? "", "base64url").toString("utf8"))
|
|
659
|
+
);
|
|
660
|
+
} catch {
|
|
661
|
+
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
662
|
+
}
|
|
663
|
+
if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
|
|
664
|
+
throw new MachineAuthError(
|
|
665
|
+
"token_identity_mismatch",
|
|
666
|
+
"The token does not match the configured machine and deployment."
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
return {
|
|
670
|
+
accessToken: data.access_token,
|
|
671
|
+
expiresAt: Math.min(Date.now() + data.expires_in * 1e3, claims.exp * 1e3)
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
function parseMachineIdentity(value, clientId) {
|
|
675
|
+
const data = machineRecord(value);
|
|
676
|
+
const principal = machineRecord(data.principal);
|
|
677
|
+
if (data.authenticated !== true || data.captureAuthorityKind !== "workos_m2m" || ![2, 3].includes(data.organizationBindingVersion) || (data.organizationBindingVersion === 3 ? !machineString(principal.authorizedUserId, 256) : principal.authorizedUserId !== void 0) || principal.kind !== "machine" || principal.clientId !== clientId || !machineString(principal.machineId, 256) || !machineString(principal.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.workosOrganizationId, 256) || !Array.isArray(principal.scopes) || !principal.scopes.every((scope) => machineString(scope, 128))) {
|
|
678
|
+
throw new MachineAuthError(
|
|
679
|
+
"machine_identity_rejected",
|
|
680
|
+
"The API did not verify a machine identity.",
|
|
681
|
+
true
|
|
682
|
+
);
|
|
683
|
+
}
|
|
684
|
+
return {
|
|
685
|
+
machineId: principal.machineId,
|
|
686
|
+
...data.organizationBindingVersion === 3 ? { authorizedUserId: principal.authorizedUserId } : {},
|
|
687
|
+
clientId,
|
|
688
|
+
displayName: principal.displayName,
|
|
689
|
+
organizationId: data.organizationId,
|
|
690
|
+
workosOrganizationId: data.workosOrganizationId,
|
|
691
|
+
scopes: principal.scopes
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetchImpl = fetch) {
|
|
695
|
+
const response = await fetchMachine(
|
|
696
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
697
|
+
{
|
|
698
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
699
|
+
redirect: "error",
|
|
700
|
+
signal: machineSignal(signal)
|
|
701
|
+
},
|
|
702
|
+
fetchImpl
|
|
703
|
+
);
|
|
704
|
+
if (!response.ok) {
|
|
705
|
+
const terminal = response.status === 401 || response.status === 403;
|
|
706
|
+
throw new MachineAuthError(
|
|
707
|
+
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
708
|
+
terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
|
|
709
|
+
terminal
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/lib/paths.ts
|
|
716
|
+
import { homedir } from "os";
|
|
717
|
+
import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
|
|
718
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
719
|
+
function absolutePath(value, variable) {
|
|
720
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
721
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
722
|
+
}
|
|
723
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
724
|
+
const normalized = normalize(value);
|
|
725
|
+
return normalized === value ? value : void 0;
|
|
726
|
+
}
|
|
727
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
728
|
+
const env = options.env ?? process.env;
|
|
729
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
730
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
731
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
732
|
+
if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
|
|
733
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
734
|
+
if (!home) {
|
|
735
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
736
|
+
}
|
|
737
|
+
return { path: join3(home, ".config", "prim"), source: "default" };
|
|
738
|
+
}
|
|
739
|
+
function primConfigDirectory(options = {}) {
|
|
740
|
+
return resolvePrimConfigDirectory(options).path;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// src/lib/machine-broker.ts
|
|
744
|
+
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
745
|
+
var IDLE_MS = 5 * 6e4;
|
|
746
|
+
function descriptorPath(directory, generation) {
|
|
747
|
+
return join4(directory, `machine_broker_${generation}.json`);
|
|
748
|
+
}
|
|
749
|
+
function readDescriptor(path) {
|
|
750
|
+
try {
|
|
751
|
+
const stat = lstatSync(path);
|
|
752
|
+
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
753
|
+
return void 0;
|
|
754
|
+
const data = JSON.parse(readFileSync3(path, "utf8"));
|
|
755
|
+
return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
|
|
756
|
+
} catch {
|
|
757
|
+
return void 0;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
function signature(secret, nonce, body) {
|
|
761
|
+
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
762
|
+
}
|
|
763
|
+
function matches(left, right) {
|
|
764
|
+
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
765
|
+
}
|
|
766
|
+
function tokenHash(token) {
|
|
767
|
+
return token ? createHash("sha256").update(token).digest("hex") : void 0;
|
|
768
|
+
}
|
|
769
|
+
async function brokerRequest(descriptor, environment, options) {
|
|
770
|
+
const body = JSON.stringify({
|
|
771
|
+
generation: environment.generation,
|
|
772
|
+
force: options.force === true,
|
|
773
|
+
observedTokenHash: tokenHash(options.observedToken),
|
|
774
|
+
timestamp: Date.now()
|
|
775
|
+
});
|
|
776
|
+
const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
777
|
+
method: "POST",
|
|
778
|
+
body,
|
|
779
|
+
redirect: "error",
|
|
780
|
+
signal: options.signal,
|
|
781
|
+
headers: {
|
|
782
|
+
"Content-Type": "application/json",
|
|
783
|
+
"X-Prim-Proof": signature(environment.clientSecret, descriptor.nonce, body)
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_RESPONSE_BYTES));
|
|
787
|
+
if (typeof envelope.body !== "string" || !matches(signature(environment.clientSecret, descriptor.nonce, envelope.body), envelope.proof))
|
|
788
|
+
throw new MachineAuthError(
|
|
789
|
+
"broker_unavailable",
|
|
790
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
791
|
+
);
|
|
792
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
793
|
+
if (data.error) {
|
|
794
|
+
const error = machineRecord(data.error);
|
|
795
|
+
throw new MachineAuthError(
|
|
796
|
+
String(error.code),
|
|
797
|
+
String(error.message),
|
|
798
|
+
error.terminal === true,
|
|
799
|
+
typeof error.retryAt === "number" ? error.retryAt : void 0
|
|
800
|
+
);
|
|
801
|
+
}
|
|
802
|
+
const credential = data.credential;
|
|
803
|
+
if (credential?.generation !== environment.generation || credential.clientId !== environment.clientId || credential.storage !== "environment")
|
|
804
|
+
throw new MachineAuthError(
|
|
805
|
+
"identity_changed",
|
|
806
|
+
"Machine identity changed; restart the operation."
|
|
807
|
+
);
|
|
808
|
+
return credential;
|
|
809
|
+
}
|
|
810
|
+
async function acquireBrokerCredential(options) {
|
|
811
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
812
|
+
const existing = readDescriptor(path);
|
|
813
|
+
if (existing) {
|
|
814
|
+
try {
|
|
815
|
+
return await brokerRequest(existing, options.environment, options);
|
|
816
|
+
} catch (error) {
|
|
817
|
+
options.signal.throwIfAborted();
|
|
818
|
+
if (error instanceof MachineAuthError) throw error;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
const descriptor = await withFileLock(
|
|
822
|
+
join4(options.directory, "machine-broker.lock"),
|
|
823
|
+
async () => {
|
|
824
|
+
const current = readDescriptor(path);
|
|
825
|
+
if (current) {
|
|
826
|
+
try {
|
|
827
|
+
const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
|
|
828
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
|
|
829
|
+
redirect: "error"
|
|
830
|
+
});
|
|
831
|
+
if (response.ok && await response.text() === current.nonce) return current;
|
|
832
|
+
} catch {
|
|
833
|
+
options.signal.throwIfAborted();
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
const bundled = fileURLToPath2(import.meta.url);
|
|
837
|
+
const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
838
|
+
if (!entry)
|
|
839
|
+
throw new MachineAuthError(
|
|
840
|
+
"broker_unavailable",
|
|
841
|
+
"Reinstall Prim to restore its machine credential broker."
|
|
842
|
+
);
|
|
843
|
+
await new Promise((resolve3, reject) => {
|
|
844
|
+
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
845
|
+
detached: true,
|
|
846
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
847
|
+
windowsHide: true,
|
|
848
|
+
env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
|
|
849
|
+
});
|
|
850
|
+
let settled = false;
|
|
851
|
+
const finish = (error) => {
|
|
852
|
+
if (settled) return;
|
|
853
|
+
settled = true;
|
|
854
|
+
options.signal.removeEventListener("abort", abort);
|
|
855
|
+
if (error) child.kill();
|
|
856
|
+
if (child.connected) child.disconnect();
|
|
857
|
+
child.unref();
|
|
858
|
+
error ? reject(error) : resolve3();
|
|
859
|
+
};
|
|
860
|
+
const abort = () => finish(
|
|
861
|
+
new MachineAuthError(
|
|
862
|
+
"broker_unavailable",
|
|
863
|
+
"Machine credential broker startup was cancelled."
|
|
864
|
+
)
|
|
865
|
+
);
|
|
866
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
867
|
+
child.once(
|
|
868
|
+
"error",
|
|
869
|
+
() => finish(
|
|
870
|
+
new MachineAuthError(
|
|
871
|
+
"broker_unavailable",
|
|
872
|
+
"Machine credential broker could not start."
|
|
873
|
+
)
|
|
874
|
+
)
|
|
875
|
+
);
|
|
876
|
+
child.once(
|
|
877
|
+
"exit",
|
|
878
|
+
() => finish(
|
|
879
|
+
new MachineAuthError(
|
|
880
|
+
"broker_unavailable",
|
|
881
|
+
"Machine credential broker exited during startup."
|
|
882
|
+
)
|
|
883
|
+
)
|
|
884
|
+
);
|
|
885
|
+
child.once("message", (message) => {
|
|
886
|
+
if (message === "ready") finish();
|
|
887
|
+
});
|
|
888
|
+
if (options.signal.aborted) abort();
|
|
889
|
+
});
|
|
890
|
+
const started = readDescriptor(path);
|
|
891
|
+
if (!started)
|
|
892
|
+
throw new MachineAuthError(
|
|
893
|
+
"broker_unavailable",
|
|
894
|
+
"Machine credential broker did not become ready."
|
|
895
|
+
);
|
|
896
|
+
return started;
|
|
897
|
+
},
|
|
898
|
+
{ signal: options.signal }
|
|
899
|
+
);
|
|
900
|
+
try {
|
|
901
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
902
|
+
} catch (error) {
|
|
903
|
+
options.signal.throwIfAborted();
|
|
904
|
+
if (error instanceof MachineAuthError) throw error;
|
|
905
|
+
throw new MachineAuthError(
|
|
906
|
+
"broker_unavailable",
|
|
907
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
// src/lib/machine-retry.ts
|
|
913
|
+
import { createHash as createHash2 } from "crypto";
|
|
914
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
915
|
+
import { join as join5 } from "path";
|
|
916
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
|
|
917
|
+
signal?.throwIfAborted();
|
|
918
|
+
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
919
|
+
const path = join5(directory, `machine_retry_${key}.json`);
|
|
920
|
+
let state = { failures: 0, retryAt: 0 };
|
|
921
|
+
try {
|
|
922
|
+
const stat = lstatSync2(path);
|
|
923
|
+
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
924
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
925
|
+
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
926
|
+
throw new Error("Invalid retry state");
|
|
927
|
+
state = data;
|
|
928
|
+
} catch (error) {
|
|
929
|
+
if (error.code !== "ENOENT")
|
|
930
|
+
throw new MachineAuthError("invalid_storage", "Machine retry state is unreadable.");
|
|
931
|
+
}
|
|
932
|
+
if (state.retryAt > Date.now())
|
|
933
|
+
throw new MachineAuthError(
|
|
934
|
+
"token_service_unavailable",
|
|
935
|
+
"Machine authentication is cooling down after a temporary failure. Retry later.",
|
|
936
|
+
false,
|
|
937
|
+
state.retryAt
|
|
938
|
+
);
|
|
939
|
+
try {
|
|
940
|
+
const result = await request2();
|
|
941
|
+
rmSync4(path, { force: true });
|
|
942
|
+
return result;
|
|
943
|
+
} catch (error) {
|
|
944
|
+
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
945
|
+
"authentication_unavailable",
|
|
946
|
+
"token_service_unavailable",
|
|
947
|
+
"verification_unavailable",
|
|
948
|
+
"discovery_unavailable"
|
|
949
|
+
].includes(error.code)) {
|
|
950
|
+
const failures = Math.min(16, state.failures + 1);
|
|
951
|
+
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
952
|
+
const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
|
|
953
|
+
atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
|
|
954
|
+
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
955
|
+
}
|
|
956
|
+
throw error;
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// src/lib/machine-credentials.ts
|
|
961
|
+
var require2 = createRequire(import.meta.url);
|
|
962
|
+
var SERVICE = "ai.primitive.prim.machine";
|
|
963
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
964
|
+
var PROFILE_FILE = "machine_profile.json";
|
|
965
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
966
|
+
var cached;
|
|
967
|
+
function configurationDirectory(deps) {
|
|
968
|
+
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
969
|
+
}
|
|
970
|
+
function apiUrlFor(deps) {
|
|
971
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
972
|
+
}
|
|
973
|
+
function hash(value) {
|
|
974
|
+
return createHash3("sha256").update(value).digest("hex");
|
|
975
|
+
}
|
|
976
|
+
function recordPath(directory, generation) {
|
|
977
|
+
return join6(directory, `machine_${generation}.json`);
|
|
978
|
+
}
|
|
979
|
+
function storageKey(directory, generation) {
|
|
980
|
+
return `${hash(directory)}:${generation}`;
|
|
981
|
+
}
|
|
982
|
+
function environmentContextPath(deps, clientId) {
|
|
983
|
+
return join6(
|
|
984
|
+
configurationDirectory(deps),
|
|
985
|
+
`machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
function writeEnvironmentContext(credential, deps) {
|
|
989
|
+
const {
|
|
990
|
+
apiUrl,
|
|
991
|
+
issuer,
|
|
992
|
+
audience,
|
|
993
|
+
generation,
|
|
994
|
+
machineId,
|
|
995
|
+
clientId,
|
|
996
|
+
organizationId,
|
|
997
|
+
workosOrganizationId,
|
|
998
|
+
displayName,
|
|
999
|
+
authorizedUserId,
|
|
1000
|
+
scopes,
|
|
1001
|
+
expiresAt
|
|
1002
|
+
} = credential;
|
|
1003
|
+
try {
|
|
1004
|
+
writePrivate(environmentContextPath(deps, clientId), {
|
|
1005
|
+
version: 1,
|
|
1006
|
+
apiUrl,
|
|
1007
|
+
issuer,
|
|
1008
|
+
audience,
|
|
1009
|
+
generation,
|
|
1010
|
+
machineId,
|
|
1011
|
+
clientId,
|
|
1012
|
+
organizationId,
|
|
1013
|
+
workosOrganizationId,
|
|
1014
|
+
displayName,
|
|
1015
|
+
authorizedUserId,
|
|
1016
|
+
scopes,
|
|
1017
|
+
expiresAt
|
|
1018
|
+
});
|
|
1019
|
+
} catch {
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
function readEnvironmentContext(environment, deps) {
|
|
1023
|
+
try {
|
|
1024
|
+
const data = machineRecord(readPrivate(environmentContextPath(deps, environment.clientId)));
|
|
1025
|
+
if (data.generation !== environment.generation || data.clientId !== environment.clientId || data.apiUrl !== apiUrlFor(deps) || typeof data.expiresAt !== "number" || !Number.isFinite(data.expiresAt) || data.expiresAt <= Date.now())
|
|
1026
|
+
return void 0;
|
|
1027
|
+
const configuration = parseMachineConfiguration({
|
|
1028
|
+
protocol_version: data.version,
|
|
1029
|
+
issuer: data.issuer,
|
|
1030
|
+
audience: data.audience
|
|
1031
|
+
});
|
|
1032
|
+
const identity = parseStoredIdentity(data);
|
|
1033
|
+
return {
|
|
1034
|
+
...configuration,
|
|
1035
|
+
...identity,
|
|
1036
|
+
apiUrl: data.apiUrl,
|
|
1037
|
+
generation: environment.generation
|
|
1038
|
+
};
|
|
1039
|
+
} catch {
|
|
1040
|
+
return void 0;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
function keyringEntry(key) {
|
|
1044
|
+
let directory = dirname4(fileURLToPath3(import.meta.url));
|
|
1045
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
1046
|
+
const loader = join6(directory, "native", "keyring.cjs");
|
|
1047
|
+
if (existsSync3(loader)) {
|
|
1048
|
+
const module2 = require2(loader);
|
|
1049
|
+
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1050
|
+
}
|
|
1051
|
+
directory = dirname4(directory);
|
|
1052
|
+
}
|
|
1053
|
+
const module = require2("@napi-rs/keyring");
|
|
1054
|
+
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1055
|
+
}
|
|
1056
|
+
function protectPath(path, directory) {
|
|
1057
|
+
if (process.platform !== "win32") {
|
|
1058
|
+
chmodSync(path, directory ? 448 : 384);
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
const encodedPath = Buffer.from(path).toString("base64");
|
|
1062
|
+
const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
|
|
1063
|
+
execFileSync(
|
|
1064
|
+
"powershell.exe",
|
|
1065
|
+
[
|
|
1066
|
+
"-NoProfile",
|
|
1067
|
+
"-NonInteractive",
|
|
1068
|
+
"-EncodedCommand",
|
|
1069
|
+
Buffer.from(script, "utf16le").toString("base64")
|
|
1070
|
+
],
|
|
1071
|
+
{ stdio: "pipe", encoding: "utf8", windowsHide: true }
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
function ensureDirectory(directory) {
|
|
1075
|
+
mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
1076
|
+
if (lstatSync3(directory).isSymbolicLink())
|
|
1077
|
+
throw new MachineAuthError(
|
|
1078
|
+
"unsafe_storage",
|
|
1079
|
+
"Credential directory must not be a symbolic link."
|
|
1080
|
+
);
|
|
1081
|
+
protectPath(directory, true);
|
|
1082
|
+
}
|
|
1083
|
+
function writePrivate(path, value) {
|
|
1084
|
+
atomicWriteFile(path, `${JSON.stringify(value)}
|
|
1085
|
+
`, { mode: 384 });
|
|
1086
|
+
protectPath(path, false);
|
|
1087
|
+
}
|
|
1088
|
+
function readPrivate(path) {
|
|
1089
|
+
let raw;
|
|
1090
|
+
try {
|
|
1091
|
+
const stat = lstatSync3(path);
|
|
1092
|
+
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1093
|
+
throw new MachineAuthError(
|
|
1094
|
+
"unsafe_storage",
|
|
1095
|
+
"Machine credential files must be owner-only regular files."
|
|
1096
|
+
);
|
|
1097
|
+
}
|
|
1098
|
+
raw = readFileSync5(path, "utf8");
|
|
1099
|
+
} catch (error) {
|
|
1100
|
+
if (error.code === "ENOENT") return void 0;
|
|
1101
|
+
throw error;
|
|
1102
|
+
}
|
|
1103
|
+
try {
|
|
1104
|
+
return JSON.parse(raw);
|
|
1105
|
+
} catch {
|
|
1106
|
+
throw new MachineAuthError("invalid_storage", "Stored machine credentials are malformed.");
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
function parseStoredIdentity(data) {
|
|
1110
|
+
return parseMachineIdentity(
|
|
1111
|
+
{
|
|
1112
|
+
authenticated: true,
|
|
1113
|
+
organizationBindingVersion: data.authorizedUserId ? 3 : 2,
|
|
1114
|
+
captureAuthorityKind: "workos_m2m",
|
|
1115
|
+
organizationId: data.organizationId,
|
|
1116
|
+
workosOrganizationId: data.workosOrganizationId,
|
|
1117
|
+
principal: { ...data, kind: "machine" }
|
|
1118
|
+
},
|
|
1119
|
+
String(data.clientId)
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
function parseProfile(value) {
|
|
1123
|
+
const data = machineRecord(value);
|
|
1124
|
+
const config = parseMachineConfiguration({
|
|
1125
|
+
protocol_version: data.version,
|
|
1126
|
+
issuer: data.issuer,
|
|
1127
|
+
audience: data.audience
|
|
1128
|
+
});
|
|
1129
|
+
if (typeof data.apiUrl !== "string" || machineApiUrl(data.apiUrl) !== data.apiUrl || !machineString(data.generation, 64) || !/^[a-f0-9-]{36}$/u.test(data.generation) || data.storage !== "keychain" && data.storage !== "file" || !machineString(data.clientId, 256)) {
|
|
1130
|
+
throw new MachineAuthError("invalid_storage", "Stored machine profile is malformed.");
|
|
1131
|
+
}
|
|
1132
|
+
const identity = parseStoredIdentity(data);
|
|
1133
|
+
return {
|
|
1134
|
+
...config,
|
|
1135
|
+
...identity,
|
|
1136
|
+
version: 1,
|
|
1137
|
+
apiUrl: data.apiUrl,
|
|
1138
|
+
generation: data.generation,
|
|
1139
|
+
storage: data.storage
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
function readMachineProfile(deps = {}) {
|
|
1143
|
+
const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1144
|
+
return value === void 0 ? void 0 : parseProfile(value);
|
|
1145
|
+
}
|
|
1146
|
+
function environmentCredentials(deps) {
|
|
1147
|
+
const env = deps.env ?? process.env;
|
|
1148
|
+
const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
|
|
1149
|
+
if (clientId === void 0 && clientSecret === void 0) return void 0;
|
|
1150
|
+
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1151
|
+
throw new MachineAuthError(
|
|
1152
|
+
"incomplete_machine_credentials",
|
|
1153
|
+
"Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
return {
|
|
1157
|
+
clientId,
|
|
1158
|
+
clientSecret,
|
|
1159
|
+
generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
function hasMachineConfiguration(deps = {}) {
|
|
1163
|
+
const env = deps.env ?? process.env;
|
|
1164
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1165
|
+
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1166
|
+
throw new MachineAuthError(
|
|
1167
|
+
"conflicting_credentials",
|
|
1168
|
+
"Unset PRIM_TOKEN when using machine credentials."
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
1171
|
+
if (configured) environmentCredentials(deps);
|
|
1172
|
+
return configured;
|
|
1173
|
+
}
|
|
1174
|
+
function machineContext(deps = {}) {
|
|
1175
|
+
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1176
|
+
const environment = environmentCredentials(deps);
|
|
1177
|
+
if (environment) {
|
|
1178
|
+
if (environmentTerminal === environment.generation) return void 0;
|
|
1179
|
+
return cached?.generation === environment.generation && cached.expiresAt > Date.now() ? cached : readEnvironmentContext(environment, deps);
|
|
1180
|
+
}
|
|
1181
|
+
const profile = readMachineProfile(deps);
|
|
1182
|
+
if (profile && profile.apiUrl !== apiUrlFor(deps))
|
|
1183
|
+
throw new MachineAuthError(
|
|
1184
|
+
"deployment_mismatch",
|
|
1185
|
+
"Machine credentials belong to another API deployment. Configure this deployment or inject its credentials."
|
|
1186
|
+
);
|
|
1187
|
+
return profile;
|
|
1188
|
+
}
|
|
1189
|
+
function cachedMachineCredential(deps = {}) {
|
|
1190
|
+
const context = machineContext(deps);
|
|
1191
|
+
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1192
|
+
}
|
|
1193
|
+
function machineSessionEnded(deps = {}) {
|
|
1194
|
+
if (!hasMachineConfiguration(deps)) return false;
|
|
1195
|
+
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1196
|
+
if (!generation) return false;
|
|
1197
|
+
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1198
|
+
return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1199
|
+
}
|
|
1200
|
+
var environmentTerminal;
|
|
1201
|
+
async function loadRecord(profile, deps, signal) {
|
|
1202
|
+
const directory = configurationDirectory(deps);
|
|
1203
|
+
let value;
|
|
1204
|
+
try {
|
|
1205
|
+
if (profile.storage === "keychain") {
|
|
1206
|
+
const raw = await (deps.entry ?? keyringEntry)(
|
|
1207
|
+
storageKey(directory, profile.generation)
|
|
1208
|
+
).getPassword(signal);
|
|
1209
|
+
if (!raw || raw.length > 96 * 1024) throw new Error("missing");
|
|
1210
|
+
value = JSON.parse(raw);
|
|
1211
|
+
} else value = readPrivate(recordPath(directory, profile.generation));
|
|
1212
|
+
const data = machineRecord(value);
|
|
1213
|
+
const stored = parseProfile(data);
|
|
1214
|
+
if ([
|
|
1215
|
+
"apiUrl",
|
|
1216
|
+
"issuer",
|
|
1217
|
+
"audience",
|
|
1218
|
+
"generation",
|
|
1219
|
+
"storage",
|
|
1220
|
+
"machineId",
|
|
1221
|
+
"authorizedUserId",
|
|
1222
|
+
"clientId",
|
|
1223
|
+
"organizationId",
|
|
1224
|
+
"workosOrganizationId"
|
|
1225
|
+
].some(
|
|
1226
|
+
(key) => stored[key] !== profile[key]
|
|
1227
|
+
) || !machineString(data.clientSecret) || !machineString(data.accessToken, 64 * 1024) || typeof data.expiresAt !== "number" || !Number.isFinite(data.expiresAt))
|
|
1228
|
+
throw new Error("mismatch");
|
|
1229
|
+
return {
|
|
1230
|
+
...stored,
|
|
1231
|
+
clientSecret: data.clientSecret,
|
|
1232
|
+
accessToken: data.accessToken,
|
|
1233
|
+
expiresAt: data.expiresAt
|
|
1234
|
+
};
|
|
1235
|
+
} catch {
|
|
1236
|
+
throw new MachineAuthError(
|
|
1237
|
+
"storage_unavailable",
|
|
1238
|
+
`Cannot read machine credentials from ${profile.storage}. Unlock or repair that store; Prim will not use another credential.`
|
|
1239
|
+
);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
async function persistRecord(record, deps, signal) {
|
|
1243
|
+
const directory = configurationDirectory(deps);
|
|
1244
|
+
if (record.storage === "keychain") {
|
|
1245
|
+
try {
|
|
1246
|
+
await (deps.entry ?? keyringEntry)(storageKey(directory, record.generation)).setPassword(
|
|
1247
|
+
JSON.stringify(record),
|
|
1248
|
+
signal
|
|
1249
|
+
);
|
|
1250
|
+
} catch {
|
|
1251
|
+
throw new MachineAuthError(
|
|
1252
|
+
"storage_unavailable",
|
|
1253
|
+
"Cannot update the machine credential store. Unlock it and retry."
|
|
1254
|
+
);
|
|
1255
|
+
}
|
|
1256
|
+
} else writePrivate(recordPath(directory, record.generation), record);
|
|
1257
|
+
}
|
|
1258
|
+
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1259
|
+
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1260
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1261
|
+
const apiUrl = apiUrlFor(deps);
|
|
1262
|
+
const environment = environmentCredentials(deps);
|
|
1263
|
+
if (environment) {
|
|
1264
|
+
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
1265
|
+
const directory2 = configurationDirectory(deps);
|
|
1266
|
+
ensureDirectory(directory2);
|
|
1267
|
+
if (!deps.fetch && !deps.localEnvironment) {
|
|
1268
|
+
try {
|
|
1269
|
+
cached = await acquireBrokerCredential({
|
|
1270
|
+
directory: directory2,
|
|
1271
|
+
apiUrl,
|
|
1272
|
+
environment,
|
|
1273
|
+
env: deps.env ?? process.env,
|
|
1274
|
+
force: options.force,
|
|
1275
|
+
observedToken: observedToken2,
|
|
1276
|
+
signal
|
|
1277
|
+
});
|
|
1278
|
+
writeEnvironmentContext(cached, deps);
|
|
1279
|
+
return cached;
|
|
1280
|
+
} catch (error) {
|
|
1281
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1282
|
+
environmentTerminal = environment.generation;
|
|
1283
|
+
throw error;
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
return withFileLock(
|
|
1287
|
+
join6(directory2, "credentials.lock"),
|
|
1288
|
+
async () => {
|
|
1289
|
+
if (machineSessionEnded(deps))
|
|
1290
|
+
throw new MachineAuthError(
|
|
1291
|
+
"machine_credentials_rejected",
|
|
1292
|
+
"Rotate the injected machine credentials.",
|
|
1293
|
+
true
|
|
1294
|
+
);
|
|
1295
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
|
|
1296
|
+
return cached;
|
|
1297
|
+
try {
|
|
1298
|
+
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
1299
|
+
directory2,
|
|
1300
|
+
apiUrl,
|
|
1301
|
+
environment.clientId,
|
|
1302
|
+
signal,
|
|
1303
|
+
async () => {
|
|
1304
|
+
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
1305
|
+
const tokens2 = await exchangeMachineCredentials(
|
|
1306
|
+
configuration2,
|
|
1307
|
+
environment.clientId,
|
|
1308
|
+
environment.clientSecret,
|
|
1309
|
+
signal,
|
|
1310
|
+
deps.fetch
|
|
1311
|
+
);
|
|
1312
|
+
const identity2 = await verifyMachineIdentity(
|
|
1313
|
+
apiUrl,
|
|
1314
|
+
tokens2.accessToken,
|
|
1315
|
+
environment.clientId,
|
|
1316
|
+
signal,
|
|
1317
|
+
deps.fetch
|
|
1318
|
+
);
|
|
1319
|
+
return { configuration: configuration2, tokens: tokens2, identity: identity2 };
|
|
1320
|
+
}
|
|
1321
|
+
);
|
|
1322
|
+
cached = {
|
|
1323
|
+
...configuration,
|
|
1324
|
+
...tokens,
|
|
1325
|
+
...identity,
|
|
1326
|
+
apiUrl,
|
|
1327
|
+
generation: environment.generation,
|
|
1328
|
+
storage: "environment"
|
|
1329
|
+
};
|
|
1330
|
+
writeEnvironmentContext(cached, deps);
|
|
1331
|
+
return cached;
|
|
1332
|
+
} catch (error) {
|
|
1333
|
+
if (error instanceof MachineAuthError && error.terminal) {
|
|
1334
|
+
environmentTerminal = environment.generation;
|
|
1335
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1336
|
+
try {
|
|
1337
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1338
|
+
rmSync5(contextPath, { force: true });
|
|
1339
|
+
} catch {
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
throw error;
|
|
1343
|
+
}
|
|
1344
|
+
},
|
|
1345
|
+
{ signal }
|
|
1346
|
+
);
|
|
1347
|
+
}
|
|
1348
|
+
const observedToken = cachedMachineCredential(deps)?.accessToken;
|
|
1349
|
+
const expected = machineContext(deps);
|
|
1350
|
+
const directory = configurationDirectory(deps);
|
|
1351
|
+
return withFileLock(
|
|
1352
|
+
join6(directory, "credentials.lock"),
|
|
1353
|
+
async () => {
|
|
1354
|
+
const profile = readMachineProfile(deps);
|
|
1355
|
+
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
1356
|
+
throw new MachineAuthError(
|
|
1357
|
+
"identity_changed",
|
|
1358
|
+
"Machine identity changed; retry the operation."
|
|
1359
|
+
);
|
|
1360
|
+
if (machineSessionEnded(deps))
|
|
1361
|
+
throw new MachineAuthError(
|
|
1362
|
+
"machine_credentials_rejected",
|
|
1363
|
+
"Configure rotated or enabled machine credentials.",
|
|
1364
|
+
true
|
|
1365
|
+
);
|
|
1366
|
+
let record = await loadRecord(profile, deps, signal);
|
|
1367
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
|
|
1368
|
+
try {
|
|
1369
|
+
const { tokens, identity } = await withMachineCooldown(
|
|
1370
|
+
directory,
|
|
1371
|
+
apiUrl,
|
|
1372
|
+
profile.clientId,
|
|
1373
|
+
signal,
|
|
1374
|
+
async () => {
|
|
1375
|
+
const tokens2 = await exchangeMachineCredentials(
|
|
1376
|
+
profile,
|
|
1377
|
+
profile.clientId,
|
|
1378
|
+
record.clientSecret,
|
|
1379
|
+
signal,
|
|
1380
|
+
deps.fetch
|
|
1381
|
+
);
|
|
1382
|
+
const identity2 = await verifyMachineIdentity(
|
|
1383
|
+
apiUrl,
|
|
1384
|
+
tokens2.accessToken,
|
|
1385
|
+
profile.clientId,
|
|
1386
|
+
signal,
|
|
1387
|
+
deps.fetch
|
|
1388
|
+
);
|
|
1389
|
+
return { tokens: tokens2, identity: identity2 };
|
|
1390
|
+
}
|
|
1391
|
+
);
|
|
1392
|
+
if (identity.machineId !== profile.machineId || identity.authorizedUserId !== profile.authorizedUserId || identity.organizationId !== profile.organizationId || identity.workosOrganizationId !== profile.workosOrganizationId)
|
|
1393
|
+
throw new MachineAuthError(
|
|
1394
|
+
"identity_changed",
|
|
1395
|
+
"Machine identity changed; configure the new identity explicitly.",
|
|
1396
|
+
true
|
|
1397
|
+
);
|
|
1398
|
+
record = { ...record, ...identity, ...tokens };
|
|
1399
|
+
await persistRecord(record, deps, signal);
|
|
1400
|
+
} catch (error) {
|
|
1401
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1402
|
+
writePrivate(join6(directory, "machine_terminal.json"), profile.generation);
|
|
1403
|
+
throw error;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
const { clientSecret: _secret, ...credential } = record;
|
|
1407
|
+
cached = credential;
|
|
1408
|
+
return credential;
|
|
1409
|
+
},
|
|
1410
|
+
{ signal }
|
|
335
1411
|
);
|
|
336
|
-
const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
337
|
-
return {
|
|
338
|
-
accessToken,
|
|
339
|
-
refreshToken: refreshToken2,
|
|
340
|
-
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
341
|
-
};
|
|
342
1412
|
}
|
|
343
1413
|
|
|
344
1414
|
// src/lib/credentials.ts
|
|
345
1415
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
346
|
-
var TOKEN_FILE_PATH =
|
|
347
|
-
var REFRESH_TOKEN_PATH =
|
|
348
|
-
var TOKEN_EXPIRES_PATH =
|
|
349
|
-
var TERMINAL_REFRESH_PATH =
|
|
350
|
-
var CREDENTIAL_METADATA_PATH =
|
|
351
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
352
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
353
|
-
var CREDENTIAL_LOCK_PATH =
|
|
1416
|
+
var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
|
|
1417
|
+
var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
|
|
1418
|
+
var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
|
|
1419
|
+
var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
|
|
1420
|
+
var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
1421
|
+
var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
|
|
1422
|
+
var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
|
|
1423
|
+
var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
|
|
354
1424
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
355
1425
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
356
1426
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
357
1427
|
function readTrimmed(path) {
|
|
358
1428
|
try {
|
|
359
|
-
const value =
|
|
1429
|
+
const value = readFileSync6(path, "utf8").trim();
|
|
360
1430
|
return value || void 0;
|
|
361
1431
|
} catch {
|
|
362
1432
|
return void 0;
|
|
363
1433
|
}
|
|
364
1434
|
}
|
|
365
1435
|
function resolveAuthCredential(options = {}) {
|
|
1436
|
+
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
1437
|
+
const machine = cachedMachineCredential({ env: options.env });
|
|
1438
|
+
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1439
|
+
}
|
|
366
1440
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
367
1441
|
if (envToken) return { token: envToken, source: "environment" };
|
|
368
1442
|
const stored = readTrimmed(options.tokenFilePath ?? TOKEN_FILE_PATH);
|
|
@@ -389,7 +1463,7 @@ function resolveAuthCredential(options = {}) {
|
|
|
389
1463
|
return { token: stored, source: "token_file" };
|
|
390
1464
|
}
|
|
391
1465
|
function credentialFingerprint(value) {
|
|
392
|
-
return
|
|
1466
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
393
1467
|
}
|
|
394
1468
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
395
1469
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -409,7 +1483,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
409
1483
|
function readBoundedCredentialJson(path) {
|
|
410
1484
|
let raw;
|
|
411
1485
|
try {
|
|
412
|
-
raw =
|
|
1486
|
+
raw = readFileSync6(path, "utf8");
|
|
413
1487
|
} catch (error) {
|
|
414
1488
|
return error.code === "ENOENT" ? void 0 : null;
|
|
415
1489
|
}
|
|
@@ -480,153 +1554,10 @@ function jwtExpiresAt(token) {
|
|
|
480
1554
|
return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 : void 0;
|
|
481
1555
|
}
|
|
482
1556
|
|
|
483
|
-
// src/lib/file-lock.ts
|
|
484
|
-
import { randomBytes } from "crypto";
|
|
485
|
-
import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
486
|
-
import { dirname as dirname2, join as join3 } from "path";
|
|
487
|
-
|
|
488
|
-
// src/lib/process-liveness.ts
|
|
489
|
-
function processIsAlive(pid, probe = process.kill) {
|
|
490
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
491
|
-
try {
|
|
492
|
-
probe(pid, 0);
|
|
493
|
-
return true;
|
|
494
|
-
} catch (error) {
|
|
495
|
-
return error.code === "EPERM";
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// src/lib/file-lock.ts
|
|
500
|
-
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
501
|
-
var DEFAULT_POLL_MS = 50;
|
|
502
|
-
var DEFAULT_INIT_GRACE_MS = 2e3;
|
|
503
|
-
var DIRECTORY_MODE = 448;
|
|
504
|
-
var FILE_MODE = 384;
|
|
505
|
-
function ownerPath(lockDir) {
|
|
506
|
-
return join3(lockDir, "owner.json");
|
|
507
|
-
}
|
|
508
|
-
function readOwner(lockDir) {
|
|
509
|
-
try {
|
|
510
|
-
const owner = JSON.parse(readFileSync2(ownerPath(lockDir), "utf8"));
|
|
511
|
-
if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
|
|
512
|
-
return null;
|
|
513
|
-
}
|
|
514
|
-
return owner;
|
|
515
|
-
} catch {
|
|
516
|
-
return null;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
function sameOwner(a, b) {
|
|
520
|
-
return a?.pid === b.pid && a.nonce === b.nonce && a.createdAt === b.createdAt;
|
|
521
|
-
}
|
|
522
|
-
function tryTakeLock(lockDir, now) {
|
|
523
|
-
try {
|
|
524
|
-
mkdirSync2(lockDir, { mode: DIRECTORY_MODE });
|
|
525
|
-
} catch (error) {
|
|
526
|
-
if (error.code === "EEXIST") return null;
|
|
527
|
-
throw error;
|
|
528
|
-
}
|
|
529
|
-
const owner = {
|
|
530
|
-
pid: process.pid,
|
|
531
|
-
nonce: randomBytes(16).toString("hex"),
|
|
532
|
-
createdAt: now
|
|
533
|
-
};
|
|
534
|
-
try {
|
|
535
|
-
writeFileSync2(ownerPath(lockDir), `${JSON.stringify(owner)}
|
|
536
|
-
`, {
|
|
537
|
-
encoding: "utf8",
|
|
538
|
-
mode: FILE_MODE,
|
|
539
|
-
flag: "wx"
|
|
540
|
-
});
|
|
541
|
-
return owner;
|
|
542
|
-
} catch (error) {
|
|
543
|
-
rmSync2(lockDir, { recursive: true, force: true });
|
|
544
|
-
throw error;
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
function recoverStaleLock(lockDir, now, alive, initGraceMs) {
|
|
548
|
-
const owner = readOwner(lockDir);
|
|
549
|
-
if (owner) {
|
|
550
|
-
if (alive(owner.pid)) return false;
|
|
551
|
-
if (!sameOwner(readOwner(lockDir), owner)) return false;
|
|
552
|
-
rmSync2(lockDir, { recursive: true, force: true });
|
|
553
|
-
return true;
|
|
554
|
-
}
|
|
555
|
-
try {
|
|
556
|
-
const before = statSync(lockDir).mtimeMs;
|
|
557
|
-
if (now - before < initGraceMs) return false;
|
|
558
|
-
if (readOwner(lockDir)) return false;
|
|
559
|
-
if (statSync(lockDir).mtimeMs !== before) return false;
|
|
560
|
-
rmSync2(lockDir, { recursive: true, force: true });
|
|
561
|
-
return true;
|
|
562
|
-
} catch {
|
|
563
|
-
return true;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
function abortError(signal) {
|
|
567
|
-
if (signal.reason instanceof Error) return signal.reason;
|
|
568
|
-
const error = new Error("The operation was aborted");
|
|
569
|
-
error.name = "AbortError";
|
|
570
|
-
return error;
|
|
571
|
-
}
|
|
572
|
-
function throwIfAborted(signal) {
|
|
573
|
-
if (signal?.aborted) throw abortError(signal);
|
|
574
|
-
}
|
|
575
|
-
async function defaultSleep(ms, signal) {
|
|
576
|
-
if (!signal) {
|
|
577
|
-
await new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
578
|
-
return;
|
|
579
|
-
}
|
|
580
|
-
throwIfAborted(signal);
|
|
581
|
-
await new Promise((resolve3, reject) => {
|
|
582
|
-
const timer = setTimeout(() => {
|
|
583
|
-
signal.removeEventListener("abort", onAbort);
|
|
584
|
-
resolve3();
|
|
585
|
-
}, ms);
|
|
586
|
-
const onAbort = () => {
|
|
587
|
-
clearTimeout(timer);
|
|
588
|
-
reject(abortError(signal));
|
|
589
|
-
};
|
|
590
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
591
|
-
});
|
|
592
|
-
}
|
|
593
|
-
var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
594
|
-
async function withFileLock(lockDir, operation, options = {}) {
|
|
595
|
-
mkdirSync2(dirname2(lockDir), { recursive: true, mode: DIRECTORY_MODE });
|
|
596
|
-
const nowMs = options.nowMs ?? Date.now;
|
|
597
|
-
const alive = options.processAlive ?? processIsAlive;
|
|
598
|
-
const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
599
|
-
let owner = null;
|
|
600
|
-
while (!owner) {
|
|
601
|
-
throwIfAborted(options.signal);
|
|
602
|
-
const now = nowMs();
|
|
603
|
-
owner = tryTakeLock(lockDir, now);
|
|
604
|
-
if (owner) break;
|
|
605
|
-
recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
|
|
606
|
-
if (now >= deadline) {
|
|
607
|
-
throw new Error(`timed out waiting for file lock ${lockDir}`);
|
|
608
|
-
}
|
|
609
|
-
if (options.sleep) {
|
|
610
|
-
await options.sleep(options.pollMs ?? DEFAULT_POLL_MS);
|
|
611
|
-
throwIfAborted(options.signal);
|
|
612
|
-
} else {
|
|
613
|
-
await defaultSleep(options.pollMs ?? DEFAULT_POLL_MS, options.signal);
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
try {
|
|
617
|
-
throwIfAborted(options.signal);
|
|
618
|
-
return await operation();
|
|
619
|
-
} finally {
|
|
620
|
-
if (sameOwner(readOwner(lockDir), owner)) {
|
|
621
|
-
rmSync2(lockDir, { recursive: true, force: true });
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
|
|
626
1557
|
// src/daemon/client-instance-id.ts
|
|
627
|
-
import { randomBytes as
|
|
628
|
-
import { chmodSync, lstatSync, readFileSync as
|
|
629
|
-
import { join as
|
|
1558
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1559
|
+
import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
|
|
1560
|
+
import { join as join8 } from "path";
|
|
630
1561
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
631
1562
|
var INSTANCE_FILE_MODE = 384;
|
|
632
1563
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -639,17 +1570,17 @@ function isClientInstanceId(value) {
|
|
|
639
1570
|
}
|
|
640
1571
|
function ensurePrivateConfigDirectory(configDir) {
|
|
641
1572
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
642
|
-
const metadata =
|
|
1573
|
+
const metadata = lstatSync4(configDir);
|
|
643
1574
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
644
1575
|
throw new Error("prim config path must be a private directory");
|
|
645
1576
|
}
|
|
646
|
-
|
|
1577
|
+
chmodSync2(configDir, CONFIG_DIRECTORY_MODE);
|
|
647
1578
|
syncDirectory(configDir);
|
|
648
1579
|
}
|
|
649
1580
|
function readExisting(path) {
|
|
650
1581
|
let metadata;
|
|
651
1582
|
try {
|
|
652
|
-
metadata =
|
|
1583
|
+
metadata = lstatSync4(path);
|
|
653
1584
|
} catch (error) {
|
|
654
1585
|
if (error.code === "ENOENT") {
|
|
655
1586
|
return;
|
|
@@ -659,11 +1590,11 @@ function readExisting(path) {
|
|
|
659
1590
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
660
1591
|
throw new Error("stored client instance identity is invalid");
|
|
661
1592
|
}
|
|
662
|
-
|
|
1593
|
+
chmodSync2(path, INSTANCE_FILE_MODE);
|
|
663
1594
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
664
1595
|
throw new Error("stored client instance identity is invalid");
|
|
665
1596
|
}
|
|
666
|
-
const raw =
|
|
1597
|
+
const raw = readFileSync7(path, "utf8");
|
|
667
1598
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
668
1599
|
if (raw !== value && raw !== `${value}
|
|
669
1600
|
` || !isClientInstanceId(value)) {
|
|
@@ -677,8 +1608,8 @@ function atomicWrite(path, value) {
|
|
|
677
1608
|
}
|
|
678
1609
|
async function getOrCreateClientInstanceId(options) {
|
|
679
1610
|
const configDir = options.configDir;
|
|
680
|
-
const path =
|
|
681
|
-
const lockPath =
|
|
1611
|
+
const path = join8(configDir, "client_instance_id");
|
|
1612
|
+
const lockPath = join8(configDir, "client-instance.lock");
|
|
682
1613
|
ensurePrivateConfigDirectory(configDir);
|
|
683
1614
|
return withFileLock(
|
|
684
1615
|
lockPath,
|
|
@@ -687,7 +1618,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
687
1618
|
if (existing !== void 0) {
|
|
688
1619
|
return existing;
|
|
689
1620
|
}
|
|
690
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
1621
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes3(INSTANCE_ENTROPY_BYTES).toString(
|
|
691
1622
|
"base64url"
|
|
692
1623
|
)}`;
|
|
693
1624
|
if (!isClientInstanceId(generated)) {
|
|
@@ -700,50 +1631,6 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
700
1631
|
);
|
|
701
1632
|
}
|
|
702
1633
|
|
|
703
|
-
// src/lib/bin-path.ts
|
|
704
|
-
import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
|
|
705
|
-
import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5 } from "path";
|
|
706
|
-
import { fileURLToPath } from "url";
|
|
707
|
-
var PKG_NAME = "@primitive.ai/prim";
|
|
708
|
-
var ROOT_WALK_LIMIT = 6;
|
|
709
|
-
var resolvedRoot;
|
|
710
|
-
function locateRoot() {
|
|
711
|
-
if (resolvedRoot !== void 0) {
|
|
712
|
-
return resolvedRoot;
|
|
713
|
-
}
|
|
714
|
-
let dir = dirname3(fileURLToPath(import.meta.url));
|
|
715
|
-
for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
|
|
716
|
-
const manifestPath = join5(dir, "package.json");
|
|
717
|
-
if (existsSync2(manifestPath)) {
|
|
718
|
-
try {
|
|
719
|
-
const manifest = JSON.parse(readFileSync4(manifestPath, "utf-8"));
|
|
720
|
-
if (manifest.name === PKG_NAME && manifest.bin) {
|
|
721
|
-
resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
|
|
722
|
-
return resolvedRoot;
|
|
723
|
-
}
|
|
724
|
-
} catch {
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
const parent = dirname3(dir);
|
|
728
|
-
if (parent === dir) {
|
|
729
|
-
break;
|
|
730
|
-
}
|
|
731
|
-
dir = parent;
|
|
732
|
-
}
|
|
733
|
-
resolvedRoot = null;
|
|
734
|
-
return resolvedRoot;
|
|
735
|
-
}
|
|
736
|
-
function packageVersion() {
|
|
737
|
-
return locateRoot()?.version ?? null;
|
|
738
|
-
}
|
|
739
|
-
var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
740
|
-
'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
|
|
741
|
-
'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
|
|
742
|
-
'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
|
|
743
|
-
'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
|
|
744
|
-
"fi; fi; "
|
|
745
|
-
].join("");
|
|
746
|
-
|
|
747
1634
|
// src/lib/ingest-uploader.ts
|
|
748
1635
|
var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
|
|
749
1636
|
var VERSION_RE = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/u;
|
|
@@ -811,11 +1698,11 @@ function terminalSafeLine(value) {
|
|
|
811
1698
|
var CONFIG_DIR_MODE = 448;
|
|
812
1699
|
var CREDENTIAL_FILE_MODE = 384;
|
|
813
1700
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
814
|
-
var
|
|
1701
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
815
1702
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
816
1703
|
function readTrimmed2(path) {
|
|
817
1704
|
try {
|
|
818
|
-
const value =
|
|
1705
|
+
const value = readFileSync8(path, "utf8").trim();
|
|
819
1706
|
return value || void 0;
|
|
820
1707
|
} catch {
|
|
821
1708
|
return void 0;
|
|
@@ -825,26 +1712,27 @@ function getSiteUrl() {
|
|
|
825
1712
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
826
1713
|
}
|
|
827
1714
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
828
|
-
return primApiUrl?.trim() ||
|
|
1715
|
+
return primApiUrl?.trim() || DEFAULT_API_URL2;
|
|
829
1716
|
}
|
|
830
1717
|
function expiresAtFor(token, expiresIn) {
|
|
831
1718
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
832
1719
|
}
|
|
833
1720
|
function ensureConfigDirectory() {
|
|
834
|
-
const directory =
|
|
835
|
-
|
|
836
|
-
|
|
1721
|
+
const directory = dirname5(TOKEN_FILE_PATH);
|
|
1722
|
+
mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
1723
|
+
chmodSync3(directory, CONFIG_DIR_MODE);
|
|
837
1724
|
}
|
|
838
1725
|
function atomicWrite2(path, content) {
|
|
839
1726
|
ensureConfigDirectory();
|
|
840
1727
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
841
1728
|
}
|
|
842
1729
|
function removeCredentialFile(path) {
|
|
843
|
-
if (!
|
|
844
|
-
|
|
1730
|
+
if (!existsSync4(path)) return false;
|
|
1731
|
+
rmSync6(path, { force: true });
|
|
845
1732
|
return true;
|
|
846
1733
|
}
|
|
847
1734
|
function getTokenExpiresAt() {
|
|
1735
|
+
if (hasMachineConfiguration()) return cachedMachineCredential()?.expiresAt;
|
|
848
1736
|
const stored = readTrimmed2(TOKEN_EXPIRES_PATH);
|
|
849
1737
|
if (stored === void 0) return void 0;
|
|
850
1738
|
const value = Number(stored);
|
|
@@ -856,7 +1744,7 @@ function isTokenExpiringSoon(credential) {
|
|
|
856
1744
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
857
1745
|
}
|
|
858
1746
|
function refreshFingerprint(refreshToken2) {
|
|
859
|
-
return
|
|
1747
|
+
return createHash5("sha256").update(refreshToken2).digest("hex");
|
|
860
1748
|
}
|
|
861
1749
|
function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
|
|
862
1750
|
return {
|
|
@@ -921,6 +1809,7 @@ function clearTerminalFingerprint() {
|
|
|
921
1809
|
removeCredentialFile(TERMINAL_REFRESH_PATH);
|
|
922
1810
|
}
|
|
923
1811
|
function isSessionEnded() {
|
|
1812
|
+
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
924
1813
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
925
1814
|
const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
926
1815
|
const ended = terminalFingerprint();
|
|
@@ -1161,6 +2050,8 @@ async function performTokenRefresh(options = {}) {
|
|
|
1161
2050
|
}
|
|
1162
2051
|
var _refreshInFlight;
|
|
1163
2052
|
function refreshToken(options = {}) {
|
|
2053
|
+
if (hasMachineConfiguration())
|
|
2054
|
+
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
1164
2055
|
if (_refreshInFlight) return _refreshInFlight;
|
|
1165
2056
|
const attempt = performTokenRefresh(options).then((token) => {
|
|
1166
2057
|
if (token) _cachedCredential = { token, source: "token_file" };
|
|
@@ -1181,7 +2072,29 @@ var HttpError = class extends Error {
|
|
|
1181
2072
|
this.body = body;
|
|
1182
2073
|
}
|
|
1183
2074
|
};
|
|
2075
|
+
var CliManagementResponseError = class extends Error {
|
|
2076
|
+
constructor() {
|
|
2077
|
+
super("Invalid API-key management response");
|
|
2078
|
+
this.name = "CliManagementResponseError";
|
|
2079
|
+
}
|
|
2080
|
+
};
|
|
1184
2081
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
2082
|
+
async function managementResponseValue(response) {
|
|
2083
|
+
if (response.status === 401) {
|
|
2084
|
+
throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
|
|
2085
|
+
}
|
|
2086
|
+
let value;
|
|
2087
|
+
try {
|
|
2088
|
+
value = await readBoundedJson(response, CLI_MANAGEMENT_RESPONSE_MAX_BYTES);
|
|
2089
|
+
} catch {
|
|
2090
|
+
if (response.ok) throw new CliManagementResponseError();
|
|
2091
|
+
throw new HttpError(response.status, `HTTP ${response.status}`, null);
|
|
2092
|
+
}
|
|
2093
|
+
if (!response.ok) {
|
|
2094
|
+
throw new HttpError(response.status, `HTTP ${response.status}`, value);
|
|
2095
|
+
}
|
|
2096
|
+
return value;
|
|
2097
|
+
}
|
|
1185
2098
|
var _cachedCredential;
|
|
1186
2099
|
function selectedCredential() {
|
|
1187
2100
|
const resolved = resolveAuthCredential();
|
|
@@ -1199,7 +2112,8 @@ async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
|
1199
2112
|
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
1200
2113
|
},
|
|
1201
2114
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
1202
|
-
signal: options?.signal
|
|
2115
|
+
signal: options?.signal,
|
|
2116
|
+
redirect: options?.redirect
|
|
1203
2117
|
});
|
|
1204
2118
|
}
|
|
1205
2119
|
async function responseValue(response) {
|
|
@@ -1214,7 +2128,66 @@ async function responseValue(response) {
|
|
|
1214
2128
|
}
|
|
1215
2129
|
return publicDecisionResponse(await response.json());
|
|
1216
2130
|
}
|
|
2131
|
+
async function machineClient(options = {}, management = false) {
|
|
2132
|
+
let credential;
|
|
2133
|
+
try {
|
|
2134
|
+
credential = await acquireMachineCredential(options);
|
|
2135
|
+
} catch (error) {
|
|
2136
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
2137
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
2138
|
+
}
|
|
2139
|
+
if (!credential) return void 0;
|
|
2140
|
+
const selected = credential;
|
|
2141
|
+
const parse = management ? managementResponseValue : responseValue;
|
|
2142
|
+
const send = async (method, path, body, requestOptions = {}) => {
|
|
2143
|
+
if (machineContext()?.generation !== selected.generation) {
|
|
2144
|
+
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2145
|
+
}
|
|
2146
|
+
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
2147
|
+
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
2148
|
+
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2149
|
+
let response = await fetchWithToken(
|
|
2150
|
+
method,
|
|
2151
|
+
path,
|
|
2152
|
+
body,
|
|
2153
|
+
{ ...requestOptions, redirect: "error" },
|
|
2154
|
+
current.accessToken,
|
|
2155
|
+
selected.apiUrl
|
|
2156
|
+
);
|
|
2157
|
+
if (response.status === 401) {
|
|
2158
|
+
const renewed = await acquireMachineCredential({
|
|
2159
|
+
force: true,
|
|
2160
|
+
signal: requestOptions.signal
|
|
2161
|
+
});
|
|
2162
|
+
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
2163
|
+
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2164
|
+
}
|
|
2165
|
+
response = await fetchWithToken(
|
|
2166
|
+
method,
|
|
2167
|
+
path,
|
|
2168
|
+
body,
|
|
2169
|
+
{ ...requestOptions, redirect: "error" },
|
|
2170
|
+
renewed.accessToken,
|
|
2171
|
+
renewed.apiUrl
|
|
2172
|
+
);
|
|
2173
|
+
}
|
|
2174
|
+
if (response.status === 401)
|
|
2175
|
+
throw new HttpError(
|
|
2176
|
+
401,
|
|
2177
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2178
|
+
);
|
|
2179
|
+
return parse(response);
|
|
2180
|
+
};
|
|
2181
|
+
return {
|
|
2182
|
+
get: (path, opts) => send("GET", path, void 0, opts),
|
|
2183
|
+
post: (path, body, opts) => send("POST", path, body, opts),
|
|
2184
|
+
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
2185
|
+
};
|
|
2186
|
+
}
|
|
1217
2187
|
async function request(method, path, body, options) {
|
|
2188
|
+
const machine = await machineClient(options);
|
|
2189
|
+
if (machine)
|
|
2190
|
+
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
1218
2191
|
const siteUrl = getSiteUrl();
|
|
1219
2192
|
let credential = selectedCredential();
|
|
1220
2193
|
let refreshAttempted = false;
|
|
@@ -1259,15 +2232,25 @@ function getClient() {
|
|
|
1259
2232
|
}
|
|
1260
2233
|
|
|
1261
2234
|
// src/daemon/principal.ts
|
|
1262
|
-
import { createHash as
|
|
2235
|
+
import { createHash as createHash6 } from "crypto";
|
|
1263
2236
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
1264
2237
|
function boundedClaim(value) {
|
|
1265
2238
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
1266
2239
|
}
|
|
1267
2240
|
function sha256(value) {
|
|
1268
|
-
return
|
|
2241
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
1269
2242
|
}
|
|
1270
2243
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
2244
|
+
if (hasMachineConfiguration()) {
|
|
2245
|
+
const machine = machineContext();
|
|
2246
|
+
return machine ? {
|
|
2247
|
+
principalId: sha256(
|
|
2248
|
+
`${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
|
|
2249
|
+
),
|
|
2250
|
+
organizationId: machine.workosOrganizationId,
|
|
2251
|
+
credentialFingerprint: sha256(machine.generation)
|
|
2252
|
+
} : void 0;
|
|
2253
|
+
}
|
|
1271
2254
|
if (!token) return void 0;
|
|
1272
2255
|
const payload = decodeJwtPayload(token);
|
|
1273
2256
|
const subject = boundedClaim(payload?.sub);
|
|
@@ -1306,8 +2289,8 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
1306
2289
|
|
|
1307
2290
|
// src/daemon/client.ts
|
|
1308
2291
|
import { createConnection } from "net";
|
|
1309
|
-
import { join as
|
|
1310
|
-
var SOCK_PATH =
|
|
2292
|
+
import { join as join10 } from "path";
|
|
2293
|
+
var SOCK_PATH = join10(primConfigDirectory(), "sock");
|
|
1311
2294
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
1312
2295
|
var nextRequestId = 1;
|
|
1313
2296
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -1421,26 +2404,26 @@ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_T
|
|
|
1421
2404
|
}
|
|
1422
2405
|
|
|
1423
2406
|
// src/lib/activation.ts
|
|
1424
|
-
import { execFileSync as
|
|
1425
|
-
import { existsSync as
|
|
2407
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
2408
|
+
import { existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
|
|
1426
2409
|
import { homedir as homedir2 } from "os";
|
|
1427
|
-
import { join as
|
|
2410
|
+
import { join as join11 } from "path";
|
|
1428
2411
|
|
|
1429
2412
|
// src/lib/demo-pause.ts
|
|
1430
|
-
import { execFileSync } from "child_process";
|
|
2413
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
1431
2414
|
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
1432
2415
|
|
|
1433
2416
|
// src/lib/git.ts
|
|
1434
|
-
import { execFileSync as
|
|
1435
|
-
import { createHash as
|
|
1436
|
-
import { lstatSync as
|
|
1437
|
-
import { basename, dirname as
|
|
2417
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
2418
|
+
import { createHash as createHash7 } from "crypto";
|
|
2419
|
+
import { lstatSync as lstatSync5, realpathSync } from "fs";
|
|
2420
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
|
|
1438
2421
|
var GIT_TIMEOUT_MS = 1e3;
|
|
1439
2422
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
1440
2423
|
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
1441
2424
|
function gitToplevel(cwd) {
|
|
1442
2425
|
try {
|
|
1443
|
-
return
|
|
2426
|
+
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
1444
2427
|
cwd,
|
|
1445
2428
|
encoding: "utf-8",
|
|
1446
2429
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -1452,7 +2435,7 @@ function gitToplevel(cwd) {
|
|
|
1452
2435
|
}
|
|
1453
2436
|
function gitValue(cwd, args) {
|
|
1454
2437
|
try {
|
|
1455
|
-
const value =
|
|
2438
|
+
const value = execFileSync3("git", args, {
|
|
1456
2439
|
cwd,
|
|
1457
2440
|
encoding: "utf-8",
|
|
1458
2441
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -1493,12 +2476,12 @@ function nearestExistingAncestor(path) {
|
|
|
1493
2476
|
let cursor = path;
|
|
1494
2477
|
while (true) {
|
|
1495
2478
|
try {
|
|
1496
|
-
|
|
2479
|
+
lstatSync5(cursor);
|
|
1497
2480
|
break;
|
|
1498
2481
|
} catch (error) {
|
|
1499
2482
|
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
1500
2483
|
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
1501
|
-
const parent =
|
|
2484
|
+
const parent = dirname6(cursor);
|
|
1502
2485
|
if (parent === cursor) return null;
|
|
1503
2486
|
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
1504
2487
|
cursor = parent;
|
|
@@ -1531,7 +2514,7 @@ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonical
|
|
|
1531
2514
|
const absolute = resolve2(cwd, filePath);
|
|
1532
2515
|
let target;
|
|
1533
2516
|
try {
|
|
1534
|
-
const stat =
|
|
2517
|
+
const stat = lstatSync5(absolute);
|
|
1535
2518
|
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
1536
2519
|
target = realpathSync.native(absolute);
|
|
1537
2520
|
} catch (error) {
|
|
@@ -1539,9 +2522,9 @@ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonical
|
|
|
1539
2522
|
return null;
|
|
1540
2523
|
}
|
|
1541
2524
|
try {
|
|
1542
|
-
const parent = realpathSync.native(
|
|
1543
|
-
if (!
|
|
1544
|
-
target = resolve2(parent,
|
|
2525
|
+
const parent = realpathSync.native(dirname6(absolute));
|
|
2526
|
+
if (!lstatSync5(parent).isDirectory()) return null;
|
|
2527
|
+
target = resolve2(parent, basename2(absolute));
|
|
1545
2528
|
} catch {
|
|
1546
2529
|
return null;
|
|
1547
2530
|
}
|
|
@@ -1573,7 +2556,7 @@ function isValidRepoSyncId(value) {
|
|
|
1573
2556
|
}
|
|
1574
2557
|
function localGitConfigValue(cwd, key) {
|
|
1575
2558
|
try {
|
|
1576
|
-
const value =
|
|
2559
|
+
const value = execFileSync4("git", ["config", "--local", "--get", key], {
|
|
1577
2560
|
cwd,
|
|
1578
2561
|
encoding: "utf-8",
|
|
1579
2562
|
stdio: ["ignore", "pipe", "ignore"],
|