@primitive.ai/prim 0.1.0-alpha.123 → 0.1.0-alpha.124
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 +63 -0
- package/dist/{chunk-5ME3WD3P.js → chunk-3OKVMKK2.js} +6 -3
- package/dist/chunk-5BZWFN62.js +206 -0
- package/dist/{chunk-FXXMDO7D.js → chunk-5KPDY5GF.js} +4 -4
- package/dist/{chunk-HLMC7VS4.js → chunk-5MH2C5QG.js} +3878 -2644
- package/dist/{chunk-NMZSCSMY.js → chunk-6PSCGY2A.js} +11 -1
- package/dist/{chunk-OXW6PSPT.js → chunk-6VJ7C2B5.js} +15 -3
- package/dist/{chunk-DQ4I3FLF.js → chunk-6W72SEXC.js} +3 -3
- package/dist/{chunk-4M23K2KZ.js → chunk-6WKJWW6D.js} +2 -2
- package/dist/{chunk-3WQ7SBOZ.js → chunk-A6YTFBQ4.js} +3 -3
- package/dist/{chunk-NL5VU7EU.js → chunk-DGZX3MID.js} +3 -3
- package/dist/{chunk-4NUGCUQC.js → chunk-EER7VG3P.js} +2 -2
- package/dist/{chunk-JZC2LHS6.js → chunk-EWV7VIZ3.js} +1 -1
- package/dist/{chunk-WN7OURQ3.js → chunk-KMWXI7KO.js} +1 -1
- package/dist/{chunk-LOFMI3D4.js → chunk-KTXJJE5K.js} +2 -2
- package/dist/{chunk-4GYJHN26.js → chunk-Q2PVD5W2.js} +1575 -549
- package/dist/{chunk-S3ZIMGXV.js → chunk-QZWLZH6D.js} +76 -2
- package/dist/{chunk-CWV5ZQR6.js → chunk-TS2NX6YT.js} +5 -5
- package/dist/{chunk-GOMEWFMG.js → chunk-WLVEXOHC.js} +143 -61
- package/dist/{chunk-RUEIVZ6T.js → chunk-WQFJ5TEG.js} +2 -2
- package/dist/{chunk-T2T45KF6.js → chunk-ZMH6GJUG.js} +4 -4
- package/dist/daemon/server.js +7795 -5449
- package/dist/hook-runtime/daemon/server.js +7795 -5449
- package/dist/hook-runtime/hooks/post-commit.js +5828 -4329
- package/dist/hook-runtime/hooks/post-rewrite.js +4331 -2833
- package/dist/hook-runtime/hooks/post-tool-use.js +5241 -2891
- package/dist/hook-runtime/hooks/pre-commit.js +1253 -280
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +4177 -1971
- package/dist/hook-runtime/hooks/prim-hook.js +4718 -2478
- package/dist/hook-runtime/hooks/session-end.js +392 -139
- package/dist/hook-runtime/hooks/session-start.js +4206 -1997
- package/dist/hook-runtime/index.js +6155 -3542
- package/dist/hook-runtime/statusline-main.js +368 -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 +229 -149
- package/dist/statusline-main.js +368 -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,38 +166,221 @@ 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);
|
|
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
|
+
}
|
|
198
322
|
}
|
|
199
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("");
|
|
383
|
+
|
|
200
384
|
// src/lib/workos-connect.ts
|
|
201
385
|
var TOKEN_PATH = "/oauth2/token";
|
|
202
386
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -326,43 +510,925 @@ 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 { issuer: record.issuer, audience: record.audience };
|
|
574
|
+
}
|
|
575
|
+
function machineSignal(signal) {
|
|
576
|
+
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
577
|
+
}
|
|
578
|
+
async function fetchMachine(url, options, fetchImpl) {
|
|
579
|
+
try {
|
|
580
|
+
return await fetchImpl(url, options);
|
|
581
|
+
} catch {
|
|
582
|
+
options.signal?.throwIfAborted();
|
|
583
|
+
throw new MachineAuthError(
|
|
584
|
+
"authentication_unavailable",
|
|
585
|
+
"Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
async function readMachineJson(response, maximumBytes) {
|
|
590
|
+
try {
|
|
591
|
+
return await readBoundedJson(response, maximumBytes);
|
|
592
|
+
} catch {
|
|
593
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
597
|
+
const response = await fetchMachine(
|
|
598
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/m2m/config`,
|
|
599
|
+
{
|
|
600
|
+
signal: machineSignal(signal),
|
|
601
|
+
redirect: "error"
|
|
602
|
+
},
|
|
603
|
+
fetchImpl
|
|
604
|
+
);
|
|
605
|
+
if (!response.ok)
|
|
606
|
+
throw new MachineAuthError(
|
|
607
|
+
response.status === 404 ? "server_upgrade_required" : "discovery_unavailable",
|
|
608
|
+
response.status === 404 ? "This server does not support machine authentication yet." : "Machine authentication discovery is unavailable."
|
|
609
|
+
);
|
|
610
|
+
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
611
|
+
}
|
|
612
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
613
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
614
|
+
throw new MachineAuthError(
|
|
615
|
+
"invalid_credentials",
|
|
616
|
+
"A machine client ID and secret are required.",
|
|
617
|
+
true
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
const response = await fetchMachine(
|
|
621
|
+
`${configuration.issuer}/oauth2/token`,
|
|
622
|
+
{
|
|
623
|
+
method: "POST",
|
|
624
|
+
redirect: "error",
|
|
625
|
+
signal: machineSignal(signal),
|
|
626
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
627
|
+
body: new URLSearchParams({
|
|
628
|
+
grant_type: "client_credentials",
|
|
629
|
+
client_id: clientId,
|
|
630
|
+
client_secret: clientSecret
|
|
631
|
+
})
|
|
632
|
+
},
|
|
633
|
+
fetchImpl
|
|
634
|
+
);
|
|
635
|
+
if (!response.ok) {
|
|
636
|
+
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
637
|
+
throw new MachineAuthError(
|
|
638
|
+
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
639
|
+
terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
|
|
640
|
+
terminal,
|
|
641
|
+
terminal ? void 0 : machineRetryAt(response)
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
const data = machineRecord(await readMachineJson(response, 64 * 1024));
|
|
645
|
+
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) {
|
|
646
|
+
throw new MachineAuthError(
|
|
647
|
+
"invalid_response",
|
|
648
|
+
"The token service returned an invalid access token."
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
let claims;
|
|
652
|
+
try {
|
|
653
|
+
claims = machineRecord(
|
|
654
|
+
JSON.parse(Buffer.from(data.access_token.split(".")[1] ?? "", "base64url").toString("utf8"))
|
|
655
|
+
);
|
|
656
|
+
} catch {
|
|
657
|
+
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
658
|
+
}
|
|
659
|
+
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()) {
|
|
660
|
+
throw new MachineAuthError(
|
|
661
|
+
"token_identity_mismatch",
|
|
662
|
+
"The token does not match the configured machine and deployment."
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
return {
|
|
666
|
+
accessToken: data.access_token,
|
|
667
|
+
expiresAt: Math.min(Date.now() + data.expires_in * 1e3, claims.exp * 1e3)
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
function parseMachineIdentity(value, clientId) {
|
|
671
|
+
const data = machineRecord(value);
|
|
672
|
+
const principal = machineRecord(data.principal);
|
|
673
|
+
if (data.authenticated !== true || data.captureAuthorityKind !== "workos_m2m" || data.organizationBindingVersion !== 2 || 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))) {
|
|
674
|
+
throw new MachineAuthError(
|
|
675
|
+
"machine_identity_rejected",
|
|
676
|
+
"The API did not verify a machine identity.",
|
|
677
|
+
true
|
|
678
|
+
);
|
|
679
|
+
}
|
|
680
|
+
return {
|
|
681
|
+
machineId: principal.machineId,
|
|
682
|
+
clientId,
|
|
683
|
+
displayName: principal.displayName,
|
|
684
|
+
organizationId: data.organizationId,
|
|
685
|
+
workosOrganizationId: data.workosOrganizationId,
|
|
686
|
+
scopes: principal.scopes
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetchImpl = fetch) {
|
|
690
|
+
const response = await fetchMachine(
|
|
691
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
692
|
+
{
|
|
693
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
694
|
+
redirect: "error",
|
|
695
|
+
signal: machineSignal(signal)
|
|
696
|
+
},
|
|
697
|
+
fetchImpl
|
|
698
|
+
);
|
|
699
|
+
if (!response.ok) {
|
|
700
|
+
const terminal = response.status === 401 || response.status === 403;
|
|
701
|
+
throw new MachineAuthError(
|
|
702
|
+
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
703
|
+
terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
|
|
704
|
+
terminal
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// src/lib/paths.ts
|
|
711
|
+
import { homedir } from "os";
|
|
712
|
+
import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
|
|
713
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
714
|
+
function absolutePath(value, variable) {
|
|
715
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
716
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
717
|
+
}
|
|
718
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
719
|
+
const normalized = normalize(value);
|
|
720
|
+
return normalized === value ? value : void 0;
|
|
721
|
+
}
|
|
722
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
723
|
+
const env = options.env ?? process.env;
|
|
724
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
725
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
726
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
727
|
+
if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
|
|
728
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
729
|
+
if (!home) {
|
|
730
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
731
|
+
}
|
|
732
|
+
return { path: join3(home, ".config", "prim"), source: "default" };
|
|
733
|
+
}
|
|
734
|
+
function primConfigDirectory(options = {}) {
|
|
735
|
+
return resolvePrimConfigDirectory(options).path;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// src/lib/machine-broker.ts
|
|
739
|
+
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
740
|
+
var IDLE_MS = 5 * 6e4;
|
|
741
|
+
function descriptorPath(directory, generation) {
|
|
742
|
+
return join4(directory, `machine_broker_${generation}.json`);
|
|
743
|
+
}
|
|
744
|
+
function readDescriptor(path) {
|
|
745
|
+
try {
|
|
746
|
+
const stat = lstatSync(path);
|
|
747
|
+
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
748
|
+
return void 0;
|
|
749
|
+
const data = JSON.parse(readFileSync3(path, "utf8"));
|
|
750
|
+
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;
|
|
751
|
+
} catch {
|
|
752
|
+
return void 0;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
function signature(secret, nonce, body) {
|
|
756
|
+
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
757
|
+
}
|
|
758
|
+
function matches(left, right) {
|
|
759
|
+
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
760
|
+
}
|
|
761
|
+
function tokenHash(token) {
|
|
762
|
+
return token ? createHash("sha256").update(token).digest("hex") : void 0;
|
|
763
|
+
}
|
|
764
|
+
async function brokerRequest(descriptor, environment, options) {
|
|
765
|
+
const body = JSON.stringify({
|
|
766
|
+
generation: environment.generation,
|
|
767
|
+
force: options.force === true,
|
|
768
|
+
observedTokenHash: tokenHash(options.observedToken),
|
|
769
|
+
timestamp: Date.now()
|
|
770
|
+
});
|
|
771
|
+
const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
772
|
+
method: "POST",
|
|
773
|
+
body,
|
|
774
|
+
redirect: "error",
|
|
775
|
+
signal: options.signal,
|
|
776
|
+
headers: {
|
|
777
|
+
"Content-Type": "application/json",
|
|
778
|
+
"X-Prim-Proof": signature(environment.clientSecret, descriptor.nonce, body)
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_RESPONSE_BYTES));
|
|
782
|
+
if (typeof envelope.body !== "string" || !matches(signature(environment.clientSecret, descriptor.nonce, envelope.body), envelope.proof))
|
|
783
|
+
throw new MachineAuthError(
|
|
784
|
+
"broker_unavailable",
|
|
785
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
786
|
+
);
|
|
787
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
788
|
+
if (data.error) {
|
|
789
|
+
const error = machineRecord(data.error);
|
|
790
|
+
throw new MachineAuthError(
|
|
791
|
+
String(error.code),
|
|
792
|
+
String(error.message),
|
|
793
|
+
error.terminal === true,
|
|
794
|
+
typeof error.retryAt === "number" ? error.retryAt : void 0
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
const credential = data.credential;
|
|
798
|
+
if (credential?.generation !== environment.generation || credential.clientId !== environment.clientId || credential.storage !== "environment")
|
|
799
|
+
throw new MachineAuthError(
|
|
800
|
+
"identity_changed",
|
|
801
|
+
"Machine identity changed; restart the operation."
|
|
802
|
+
);
|
|
803
|
+
return credential;
|
|
804
|
+
}
|
|
805
|
+
async function acquireBrokerCredential(options) {
|
|
806
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
807
|
+
const existing = readDescriptor(path);
|
|
808
|
+
if (existing) {
|
|
809
|
+
try {
|
|
810
|
+
return await brokerRequest(existing, options.environment, options);
|
|
811
|
+
} catch (error) {
|
|
812
|
+
options.signal.throwIfAborted();
|
|
813
|
+
if (error instanceof MachineAuthError) throw error;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
const descriptor = await withFileLock(
|
|
817
|
+
join4(options.directory, "machine-broker.lock"),
|
|
818
|
+
async () => {
|
|
819
|
+
const current = readDescriptor(path);
|
|
820
|
+
if (current) {
|
|
821
|
+
try {
|
|
822
|
+
const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
|
|
823
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
|
|
824
|
+
redirect: "error"
|
|
825
|
+
});
|
|
826
|
+
if (response.ok && await response.text() === current.nonce) return current;
|
|
827
|
+
} catch {
|
|
828
|
+
options.signal.throwIfAborted();
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
const bundled = fileURLToPath2(import.meta.url);
|
|
832
|
+
const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
833
|
+
if (!entry)
|
|
834
|
+
throw new MachineAuthError(
|
|
835
|
+
"broker_unavailable",
|
|
836
|
+
"Reinstall Prim to restore its machine credential broker."
|
|
837
|
+
);
|
|
838
|
+
await new Promise((resolve3, reject) => {
|
|
839
|
+
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
840
|
+
detached: true,
|
|
841
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
842
|
+
windowsHide: true,
|
|
843
|
+
env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
|
|
844
|
+
});
|
|
845
|
+
let settled = false;
|
|
846
|
+
const finish = (error) => {
|
|
847
|
+
if (settled) return;
|
|
848
|
+
settled = true;
|
|
849
|
+
options.signal.removeEventListener("abort", abort);
|
|
850
|
+
if (error) child.kill();
|
|
851
|
+
if (child.connected) child.disconnect();
|
|
852
|
+
child.unref();
|
|
853
|
+
error ? reject(error) : resolve3();
|
|
854
|
+
};
|
|
855
|
+
const abort = () => finish(
|
|
856
|
+
new MachineAuthError(
|
|
857
|
+
"broker_unavailable",
|
|
858
|
+
"Machine credential broker startup was cancelled."
|
|
859
|
+
)
|
|
860
|
+
);
|
|
861
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
862
|
+
child.once(
|
|
863
|
+
"error",
|
|
864
|
+
() => finish(
|
|
865
|
+
new MachineAuthError(
|
|
866
|
+
"broker_unavailable",
|
|
867
|
+
"Machine credential broker could not start."
|
|
868
|
+
)
|
|
869
|
+
)
|
|
870
|
+
);
|
|
871
|
+
child.once(
|
|
872
|
+
"exit",
|
|
873
|
+
() => finish(
|
|
874
|
+
new MachineAuthError(
|
|
875
|
+
"broker_unavailable",
|
|
876
|
+
"Machine credential broker exited during startup."
|
|
877
|
+
)
|
|
878
|
+
)
|
|
879
|
+
);
|
|
880
|
+
child.once("message", (message) => {
|
|
881
|
+
if (message === "ready") finish();
|
|
882
|
+
});
|
|
883
|
+
if (options.signal.aborted) abort();
|
|
884
|
+
});
|
|
885
|
+
const started = readDescriptor(path);
|
|
886
|
+
if (!started)
|
|
887
|
+
throw new MachineAuthError(
|
|
888
|
+
"broker_unavailable",
|
|
889
|
+
"Machine credential broker did not become ready."
|
|
890
|
+
);
|
|
891
|
+
return started;
|
|
892
|
+
},
|
|
893
|
+
{ signal: options.signal }
|
|
894
|
+
);
|
|
895
|
+
try {
|
|
896
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
897
|
+
} catch (error) {
|
|
898
|
+
options.signal.throwIfAborted();
|
|
899
|
+
if (error instanceof MachineAuthError) throw error;
|
|
900
|
+
throw new MachineAuthError(
|
|
901
|
+
"broker_unavailable",
|
|
902
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
903
|
+
);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// src/lib/machine-retry.ts
|
|
908
|
+
import { createHash as createHash2 } from "crypto";
|
|
909
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
910
|
+
import { join as join5 } from "path";
|
|
911
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
|
|
912
|
+
signal?.throwIfAborted();
|
|
913
|
+
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
914
|
+
const path = join5(directory, `machine_retry_${key}.json`);
|
|
915
|
+
let state = { failures: 0, retryAt: 0 };
|
|
916
|
+
try {
|
|
917
|
+
const stat = lstatSync2(path);
|
|
918
|
+
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
919
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
920
|
+
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
921
|
+
throw new Error("Invalid retry state");
|
|
922
|
+
state = data;
|
|
923
|
+
} catch (error) {
|
|
924
|
+
if (error.code !== "ENOENT")
|
|
925
|
+
throw new MachineAuthError("invalid_storage", "Machine retry state is unreadable.");
|
|
926
|
+
}
|
|
927
|
+
if (state.retryAt > Date.now())
|
|
928
|
+
throw new MachineAuthError(
|
|
929
|
+
"token_service_unavailable",
|
|
930
|
+
"Machine authentication is cooling down after a temporary failure. Retry later.",
|
|
931
|
+
false,
|
|
932
|
+
state.retryAt
|
|
933
|
+
);
|
|
934
|
+
try {
|
|
935
|
+
const result = await request2();
|
|
936
|
+
rmSync4(path, { force: true });
|
|
937
|
+
return result;
|
|
938
|
+
} catch (error) {
|
|
939
|
+
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
940
|
+
"authentication_unavailable",
|
|
941
|
+
"token_service_unavailable",
|
|
942
|
+
"verification_unavailable",
|
|
943
|
+
"discovery_unavailable"
|
|
944
|
+
].includes(error.code)) {
|
|
945
|
+
const failures = Math.min(16, state.failures + 1);
|
|
946
|
+
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
947
|
+
const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
|
|
948
|
+
atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
|
|
949
|
+
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
950
|
+
}
|
|
951
|
+
throw error;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// src/lib/machine-credentials.ts
|
|
956
|
+
var require2 = createRequire(import.meta.url);
|
|
957
|
+
var SERVICE = "ai.primitive.prim.machine";
|
|
958
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
959
|
+
var PROFILE_FILE = "machine_profile.json";
|
|
960
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
961
|
+
var cached;
|
|
962
|
+
function configurationDirectory(deps) {
|
|
963
|
+
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
964
|
+
}
|
|
965
|
+
function apiUrlFor(deps) {
|
|
966
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
967
|
+
}
|
|
968
|
+
function hash(value) {
|
|
969
|
+
return createHash3("sha256").update(value).digest("hex");
|
|
970
|
+
}
|
|
971
|
+
function recordPath(directory, generation) {
|
|
972
|
+
return join6(directory, `machine_${generation}.json`);
|
|
973
|
+
}
|
|
974
|
+
function storageKey(directory, generation) {
|
|
975
|
+
return `${hash(directory)}:${generation}`;
|
|
976
|
+
}
|
|
977
|
+
function environmentContextPath(deps, clientId) {
|
|
978
|
+
return join6(
|
|
979
|
+
configurationDirectory(deps),
|
|
980
|
+
`machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
981
|
+
);
|
|
982
|
+
}
|
|
983
|
+
function writeEnvironmentContext(credential, deps) {
|
|
984
|
+
const {
|
|
985
|
+
apiUrl,
|
|
986
|
+
issuer,
|
|
987
|
+
audience,
|
|
988
|
+
generation,
|
|
989
|
+
machineId,
|
|
990
|
+
clientId,
|
|
991
|
+
organizationId,
|
|
992
|
+
workosOrganizationId,
|
|
993
|
+
displayName,
|
|
994
|
+
scopes,
|
|
995
|
+
expiresAt
|
|
996
|
+
} = credential;
|
|
997
|
+
try {
|
|
998
|
+
writePrivate(environmentContextPath(deps, clientId), {
|
|
999
|
+
version: 1,
|
|
1000
|
+
apiUrl,
|
|
1001
|
+
issuer,
|
|
1002
|
+
audience,
|
|
1003
|
+
generation,
|
|
1004
|
+
machineId,
|
|
1005
|
+
clientId,
|
|
1006
|
+
organizationId,
|
|
1007
|
+
workosOrganizationId,
|
|
1008
|
+
displayName,
|
|
1009
|
+
scopes,
|
|
1010
|
+
expiresAt
|
|
1011
|
+
});
|
|
1012
|
+
} catch {
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
function readEnvironmentContext(environment, deps) {
|
|
1016
|
+
try {
|
|
1017
|
+
const data = machineRecord(readPrivate(environmentContextPath(deps, environment.clientId)));
|
|
1018
|
+
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())
|
|
1019
|
+
return void 0;
|
|
1020
|
+
const configuration = parseMachineConfiguration({
|
|
1021
|
+
protocol_version: data.version,
|
|
1022
|
+
issuer: data.issuer,
|
|
1023
|
+
audience: data.audience
|
|
1024
|
+
});
|
|
1025
|
+
const identity = parseStoredIdentity(data);
|
|
1026
|
+
return {
|
|
1027
|
+
...configuration,
|
|
1028
|
+
...identity,
|
|
1029
|
+
apiUrl: data.apiUrl,
|
|
1030
|
+
generation: environment.generation
|
|
1031
|
+
};
|
|
1032
|
+
} catch {
|
|
1033
|
+
return void 0;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
function keyringEntry(key) {
|
|
1037
|
+
let directory = dirname4(fileURLToPath3(import.meta.url));
|
|
1038
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
1039
|
+
const loader = join6(directory, "native", "keyring.cjs");
|
|
1040
|
+
if (existsSync3(loader)) {
|
|
1041
|
+
const module2 = require2(loader);
|
|
1042
|
+
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1043
|
+
}
|
|
1044
|
+
directory = dirname4(directory);
|
|
1045
|
+
}
|
|
1046
|
+
const module = require2("@napi-rs/keyring");
|
|
1047
|
+
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1048
|
+
}
|
|
1049
|
+
function protectPath(path, directory) {
|
|
1050
|
+
if (process.platform !== "win32") {
|
|
1051
|
+
chmodSync(path, directory ? 448 : 384);
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
const encodedPath = Buffer.from(path).toString("base64");
|
|
1055
|
+
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)`;
|
|
1056
|
+
execFileSync(
|
|
1057
|
+
"powershell.exe",
|
|
1058
|
+
[
|
|
1059
|
+
"-NoProfile",
|
|
1060
|
+
"-NonInteractive",
|
|
1061
|
+
"-EncodedCommand",
|
|
1062
|
+
Buffer.from(script, "utf16le").toString("base64")
|
|
1063
|
+
],
|
|
1064
|
+
{ stdio: "pipe", encoding: "utf8", windowsHide: true }
|
|
1065
|
+
);
|
|
1066
|
+
}
|
|
1067
|
+
function ensureDirectory(directory) {
|
|
1068
|
+
mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
1069
|
+
if (lstatSync3(directory).isSymbolicLink())
|
|
1070
|
+
throw new MachineAuthError(
|
|
1071
|
+
"unsafe_storage",
|
|
1072
|
+
"Credential directory must not be a symbolic link."
|
|
1073
|
+
);
|
|
1074
|
+
protectPath(directory, true);
|
|
1075
|
+
}
|
|
1076
|
+
function writePrivate(path, value) {
|
|
1077
|
+
atomicWriteFile(path, `${JSON.stringify(value)}
|
|
1078
|
+
`, { mode: 384 });
|
|
1079
|
+
protectPath(path, false);
|
|
1080
|
+
}
|
|
1081
|
+
function readPrivate(path) {
|
|
1082
|
+
let raw;
|
|
1083
|
+
try {
|
|
1084
|
+
const stat = lstatSync3(path);
|
|
1085
|
+
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1086
|
+
throw new MachineAuthError(
|
|
1087
|
+
"unsafe_storage",
|
|
1088
|
+
"Machine credential files must be owner-only regular files."
|
|
1089
|
+
);
|
|
1090
|
+
}
|
|
1091
|
+
raw = readFileSync5(path, "utf8");
|
|
1092
|
+
} catch (error) {
|
|
1093
|
+
if (error.code === "ENOENT") return void 0;
|
|
1094
|
+
throw error;
|
|
1095
|
+
}
|
|
1096
|
+
try {
|
|
1097
|
+
return JSON.parse(raw);
|
|
1098
|
+
} catch {
|
|
1099
|
+
throw new MachineAuthError("invalid_storage", "Stored machine credentials are malformed.");
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
function parseStoredIdentity(data) {
|
|
1103
|
+
return parseMachineIdentity(
|
|
1104
|
+
{
|
|
1105
|
+
authenticated: true,
|
|
1106
|
+
organizationBindingVersion: 2,
|
|
1107
|
+
captureAuthorityKind: "workos_m2m",
|
|
1108
|
+
organizationId: data.organizationId,
|
|
1109
|
+
workosOrganizationId: data.workosOrganizationId,
|
|
1110
|
+
principal: { ...data, kind: "machine" }
|
|
1111
|
+
},
|
|
1112
|
+
String(data.clientId)
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
function parseProfile(value) {
|
|
1116
|
+
const data = machineRecord(value);
|
|
1117
|
+
const config = parseMachineConfiguration({
|
|
1118
|
+
protocol_version: data.version,
|
|
1119
|
+
issuer: data.issuer,
|
|
1120
|
+
audience: data.audience
|
|
1121
|
+
});
|
|
1122
|
+
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)) {
|
|
1123
|
+
throw new MachineAuthError("invalid_storage", "Stored machine profile is malformed.");
|
|
1124
|
+
}
|
|
1125
|
+
const identity = parseStoredIdentity(data);
|
|
1126
|
+
return {
|
|
1127
|
+
...config,
|
|
1128
|
+
...identity,
|
|
1129
|
+
version: 1,
|
|
1130
|
+
apiUrl: data.apiUrl,
|
|
1131
|
+
generation: data.generation,
|
|
1132
|
+
storage: data.storage
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
function readMachineProfile(deps = {}) {
|
|
1136
|
+
const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1137
|
+
return value === void 0 ? void 0 : parseProfile(value);
|
|
1138
|
+
}
|
|
1139
|
+
function environmentCredentials(deps) {
|
|
1140
|
+
const env = deps.env ?? process.env;
|
|
1141
|
+
const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
|
|
1142
|
+
if (clientId === void 0 && clientSecret === void 0) return void 0;
|
|
1143
|
+
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1144
|
+
throw new MachineAuthError(
|
|
1145
|
+
"incomplete_machine_credentials",
|
|
1146
|
+
"Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
return {
|
|
1150
|
+
clientId,
|
|
1151
|
+
clientSecret,
|
|
1152
|
+
generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
function hasMachineConfiguration(deps = {}) {
|
|
1156
|
+
const env = deps.env ?? process.env;
|
|
1157
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1158
|
+
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1159
|
+
throw new MachineAuthError(
|
|
1160
|
+
"conflicting_credentials",
|
|
1161
|
+
"Unset PRIM_TOKEN when using machine credentials."
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
if (configured) environmentCredentials(deps);
|
|
1165
|
+
return configured;
|
|
1166
|
+
}
|
|
1167
|
+
function machineContext(deps = {}) {
|
|
1168
|
+
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1169
|
+
const environment = environmentCredentials(deps);
|
|
1170
|
+
if (environment) {
|
|
1171
|
+
if (environmentTerminal === environment.generation) return void 0;
|
|
1172
|
+
return cached?.generation === environment.generation && cached.expiresAt > Date.now() ? cached : readEnvironmentContext(environment, deps);
|
|
1173
|
+
}
|
|
1174
|
+
const profile = readMachineProfile(deps);
|
|
1175
|
+
if (profile && profile.apiUrl !== apiUrlFor(deps))
|
|
1176
|
+
throw new MachineAuthError(
|
|
1177
|
+
"deployment_mismatch",
|
|
1178
|
+
"Machine credentials belong to another API deployment. Configure this deployment or inject its credentials."
|
|
1179
|
+
);
|
|
1180
|
+
return profile;
|
|
1181
|
+
}
|
|
1182
|
+
function cachedMachineCredential(deps = {}) {
|
|
1183
|
+
const context = machineContext(deps);
|
|
1184
|
+
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1185
|
+
}
|
|
1186
|
+
function machineSessionEnded(deps = {}) {
|
|
1187
|
+
if (!hasMachineConfiguration(deps)) return false;
|
|
1188
|
+
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1189
|
+
if (!generation) return false;
|
|
1190
|
+
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1191
|
+
return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1192
|
+
}
|
|
1193
|
+
var environmentTerminal;
|
|
1194
|
+
async function loadRecord(profile, deps, signal) {
|
|
1195
|
+
const directory = configurationDirectory(deps);
|
|
1196
|
+
let value;
|
|
1197
|
+
try {
|
|
1198
|
+
if (profile.storage === "keychain") {
|
|
1199
|
+
const raw = await (deps.entry ?? keyringEntry)(
|
|
1200
|
+
storageKey(directory, profile.generation)
|
|
1201
|
+
).getPassword(signal);
|
|
1202
|
+
if (!raw || raw.length > 96 * 1024) throw new Error("missing");
|
|
1203
|
+
value = JSON.parse(raw);
|
|
1204
|
+
} else value = readPrivate(recordPath(directory, profile.generation));
|
|
1205
|
+
const data = machineRecord(value);
|
|
1206
|
+
const stored = parseProfile(data);
|
|
1207
|
+
if ([
|
|
1208
|
+
"apiUrl",
|
|
1209
|
+
"issuer",
|
|
1210
|
+
"audience",
|
|
1211
|
+
"generation",
|
|
1212
|
+
"storage",
|
|
1213
|
+
"machineId",
|
|
1214
|
+
"clientId",
|
|
1215
|
+
"organizationId",
|
|
1216
|
+
"workosOrganizationId"
|
|
1217
|
+
].some(
|
|
1218
|
+
(key) => stored[key] !== profile[key]
|
|
1219
|
+
) || !machineString(data.clientSecret) || !machineString(data.accessToken, 64 * 1024) || typeof data.expiresAt !== "number" || !Number.isFinite(data.expiresAt))
|
|
1220
|
+
throw new Error("mismatch");
|
|
1221
|
+
return {
|
|
1222
|
+
...stored,
|
|
1223
|
+
clientSecret: data.clientSecret,
|
|
1224
|
+
accessToken: data.accessToken,
|
|
1225
|
+
expiresAt: data.expiresAt
|
|
1226
|
+
};
|
|
1227
|
+
} catch {
|
|
1228
|
+
throw new MachineAuthError(
|
|
1229
|
+
"storage_unavailable",
|
|
1230
|
+
`Cannot read machine credentials from ${profile.storage}. Unlock or repair that store; Prim will not use another credential.`
|
|
1231
|
+
);
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
async function persistRecord(record, deps, signal) {
|
|
1235
|
+
const directory = configurationDirectory(deps);
|
|
1236
|
+
if (record.storage === "keychain") {
|
|
1237
|
+
try {
|
|
1238
|
+
await (deps.entry ?? keyringEntry)(storageKey(directory, record.generation)).setPassword(
|
|
1239
|
+
JSON.stringify(record),
|
|
1240
|
+
signal
|
|
1241
|
+
);
|
|
1242
|
+
} catch {
|
|
1243
|
+
throw new MachineAuthError(
|
|
1244
|
+
"storage_unavailable",
|
|
1245
|
+
"Cannot update the machine credential store. Unlock it and retry."
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
} else writePrivate(recordPath(directory, record.generation), record);
|
|
1249
|
+
}
|
|
1250
|
+
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1251
|
+
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1252
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1253
|
+
const apiUrl = apiUrlFor(deps);
|
|
1254
|
+
const environment = environmentCredentials(deps);
|
|
1255
|
+
if (environment) {
|
|
1256
|
+
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
1257
|
+
const directory2 = configurationDirectory(deps);
|
|
1258
|
+
ensureDirectory(directory2);
|
|
1259
|
+
if (!deps.fetch && !deps.localEnvironment) {
|
|
1260
|
+
try {
|
|
1261
|
+
cached = await acquireBrokerCredential({
|
|
1262
|
+
directory: directory2,
|
|
1263
|
+
apiUrl,
|
|
1264
|
+
environment,
|
|
1265
|
+
env: deps.env ?? process.env,
|
|
1266
|
+
force: options.force,
|
|
1267
|
+
observedToken: observedToken2,
|
|
1268
|
+
signal
|
|
1269
|
+
});
|
|
1270
|
+
writeEnvironmentContext(cached, deps);
|
|
1271
|
+
return cached;
|
|
1272
|
+
} catch (error) {
|
|
1273
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1274
|
+
environmentTerminal = environment.generation;
|
|
1275
|
+
throw error;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
return withFileLock(
|
|
1279
|
+
join6(directory2, "credentials.lock"),
|
|
1280
|
+
async () => {
|
|
1281
|
+
if (machineSessionEnded(deps))
|
|
1282
|
+
throw new MachineAuthError(
|
|
1283
|
+
"machine_credentials_rejected",
|
|
1284
|
+
"Rotate the injected machine credentials.",
|
|
1285
|
+
true
|
|
1286
|
+
);
|
|
1287
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
|
|
1288
|
+
return cached;
|
|
1289
|
+
try {
|
|
1290
|
+
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
1291
|
+
directory2,
|
|
1292
|
+
apiUrl,
|
|
1293
|
+
environment.clientId,
|
|
1294
|
+
signal,
|
|
1295
|
+
async () => {
|
|
1296
|
+
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
1297
|
+
const tokens2 = await exchangeMachineCredentials(
|
|
1298
|
+
configuration2,
|
|
1299
|
+
environment.clientId,
|
|
1300
|
+
environment.clientSecret,
|
|
1301
|
+
signal,
|
|
1302
|
+
deps.fetch
|
|
1303
|
+
);
|
|
1304
|
+
const identity2 = await verifyMachineIdentity(
|
|
1305
|
+
apiUrl,
|
|
1306
|
+
tokens2.accessToken,
|
|
1307
|
+
environment.clientId,
|
|
1308
|
+
signal,
|
|
1309
|
+
deps.fetch
|
|
1310
|
+
);
|
|
1311
|
+
return { configuration: configuration2, tokens: tokens2, identity: identity2 };
|
|
1312
|
+
}
|
|
1313
|
+
);
|
|
1314
|
+
cached = {
|
|
1315
|
+
...configuration,
|
|
1316
|
+
...tokens,
|
|
1317
|
+
...identity,
|
|
1318
|
+
apiUrl,
|
|
1319
|
+
generation: environment.generation,
|
|
1320
|
+
storage: "environment"
|
|
1321
|
+
};
|
|
1322
|
+
writeEnvironmentContext(cached, deps);
|
|
1323
|
+
return cached;
|
|
1324
|
+
} catch (error) {
|
|
1325
|
+
if (error instanceof MachineAuthError && error.terminal) {
|
|
1326
|
+
environmentTerminal = environment.generation;
|
|
1327
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1328
|
+
try {
|
|
1329
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1330
|
+
rmSync5(contextPath, { force: true });
|
|
1331
|
+
} catch {
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
throw error;
|
|
1335
|
+
}
|
|
1336
|
+
},
|
|
1337
|
+
{ signal }
|
|
1338
|
+
);
|
|
1339
|
+
}
|
|
1340
|
+
const observedToken = cachedMachineCredential(deps)?.accessToken;
|
|
1341
|
+
const expected = machineContext(deps);
|
|
1342
|
+
const directory = configurationDirectory(deps);
|
|
1343
|
+
return withFileLock(
|
|
1344
|
+
join6(directory, "credentials.lock"),
|
|
1345
|
+
async () => {
|
|
1346
|
+
const profile = readMachineProfile(deps);
|
|
1347
|
+
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
1348
|
+
throw new MachineAuthError(
|
|
1349
|
+
"identity_changed",
|
|
1350
|
+
"Machine identity changed; retry the operation."
|
|
1351
|
+
);
|
|
1352
|
+
if (machineSessionEnded(deps))
|
|
1353
|
+
throw new MachineAuthError(
|
|
1354
|
+
"machine_credentials_rejected",
|
|
1355
|
+
"Configure rotated or enabled machine credentials.",
|
|
1356
|
+
true
|
|
1357
|
+
);
|
|
1358
|
+
let record = await loadRecord(profile, deps, signal);
|
|
1359
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
|
|
1360
|
+
try {
|
|
1361
|
+
const { tokens, identity } = await withMachineCooldown(
|
|
1362
|
+
directory,
|
|
1363
|
+
apiUrl,
|
|
1364
|
+
profile.clientId,
|
|
1365
|
+
signal,
|
|
1366
|
+
async () => {
|
|
1367
|
+
const tokens2 = await exchangeMachineCredentials(
|
|
1368
|
+
profile,
|
|
1369
|
+
profile.clientId,
|
|
1370
|
+
record.clientSecret,
|
|
1371
|
+
signal,
|
|
1372
|
+
deps.fetch
|
|
1373
|
+
);
|
|
1374
|
+
const identity2 = await verifyMachineIdentity(
|
|
1375
|
+
apiUrl,
|
|
1376
|
+
tokens2.accessToken,
|
|
1377
|
+
profile.clientId,
|
|
1378
|
+
signal,
|
|
1379
|
+
deps.fetch
|
|
1380
|
+
);
|
|
1381
|
+
return { tokens: tokens2, identity: identity2 };
|
|
1382
|
+
}
|
|
1383
|
+
);
|
|
1384
|
+
if (identity.machineId !== profile.machineId || identity.organizationId !== profile.organizationId || identity.workosOrganizationId !== profile.workosOrganizationId)
|
|
1385
|
+
throw new MachineAuthError(
|
|
1386
|
+
"identity_changed",
|
|
1387
|
+
"Machine identity changed; configure the new identity explicitly.",
|
|
1388
|
+
true
|
|
1389
|
+
);
|
|
1390
|
+
record = { ...record, ...identity, ...tokens };
|
|
1391
|
+
await persistRecord(record, deps, signal);
|
|
1392
|
+
} catch (error) {
|
|
1393
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1394
|
+
writePrivate(join6(directory, "machine_terminal.json"), profile.generation);
|
|
1395
|
+
throw error;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
const { clientSecret: _secret, ...credential } = record;
|
|
1399
|
+
cached = credential;
|
|
1400
|
+
return credential;
|
|
1401
|
+
},
|
|
1402
|
+
{ signal }
|
|
335
1403
|
);
|
|
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
1404
|
}
|
|
343
1405
|
|
|
344
1406
|
// src/lib/credentials.ts
|
|
345
1407
|
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 =
|
|
1408
|
+
var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
|
|
1409
|
+
var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
|
|
1410
|
+
var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
|
|
1411
|
+
var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
|
|
1412
|
+
var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
1413
|
+
var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
|
|
1414
|
+
var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
|
|
1415
|
+
var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
|
|
354
1416
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
355
1417
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
356
1418
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
357
1419
|
function readTrimmed(path) {
|
|
358
1420
|
try {
|
|
359
|
-
const value =
|
|
1421
|
+
const value = readFileSync6(path, "utf8").trim();
|
|
360
1422
|
return value || void 0;
|
|
361
1423
|
} catch {
|
|
362
1424
|
return void 0;
|
|
363
1425
|
}
|
|
364
1426
|
}
|
|
365
1427
|
function resolveAuthCredential(options = {}) {
|
|
1428
|
+
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
1429
|
+
const machine = cachedMachineCredential({ env: options.env });
|
|
1430
|
+
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1431
|
+
}
|
|
366
1432
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
367
1433
|
if (envToken) return { token: envToken, source: "environment" };
|
|
368
1434
|
const stored = readTrimmed(options.tokenFilePath ?? TOKEN_FILE_PATH);
|
|
@@ -389,7 +1455,7 @@ function resolveAuthCredential(options = {}) {
|
|
|
389
1455
|
return { token: stored, source: "token_file" };
|
|
390
1456
|
}
|
|
391
1457
|
function credentialFingerprint(value) {
|
|
392
|
-
return
|
|
1458
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
393
1459
|
}
|
|
394
1460
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
395
1461
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -409,7 +1475,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
409
1475
|
function readBoundedCredentialJson(path) {
|
|
410
1476
|
let raw;
|
|
411
1477
|
try {
|
|
412
|
-
raw =
|
|
1478
|
+
raw = readFileSync6(path, "utf8");
|
|
413
1479
|
} catch (error) {
|
|
414
1480
|
return error.code === "ENOENT" ? void 0 : null;
|
|
415
1481
|
}
|
|
@@ -480,153 +1546,10 @@ function jwtExpiresAt(token) {
|
|
|
480
1546
|
return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 : void 0;
|
|
481
1547
|
}
|
|
482
1548
|
|
|
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
1549
|
// src/daemon/client-instance-id.ts
|
|
627
|
-
import { randomBytes as
|
|
628
|
-
import { chmodSync, lstatSync, readFileSync as
|
|
629
|
-
import { join as
|
|
1550
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1551
|
+
import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
|
|
1552
|
+
import { join as join8 } from "path";
|
|
630
1553
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
631
1554
|
var INSTANCE_FILE_MODE = 384;
|
|
632
1555
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -639,17 +1562,17 @@ function isClientInstanceId(value) {
|
|
|
639
1562
|
}
|
|
640
1563
|
function ensurePrivateConfigDirectory(configDir) {
|
|
641
1564
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
642
|
-
const metadata =
|
|
1565
|
+
const metadata = lstatSync4(configDir);
|
|
643
1566
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
644
1567
|
throw new Error("prim config path must be a private directory");
|
|
645
1568
|
}
|
|
646
|
-
|
|
1569
|
+
chmodSync2(configDir, CONFIG_DIRECTORY_MODE);
|
|
647
1570
|
syncDirectory(configDir);
|
|
648
1571
|
}
|
|
649
1572
|
function readExisting(path) {
|
|
650
1573
|
let metadata;
|
|
651
1574
|
try {
|
|
652
|
-
metadata =
|
|
1575
|
+
metadata = lstatSync4(path);
|
|
653
1576
|
} catch (error) {
|
|
654
1577
|
if (error.code === "ENOENT") {
|
|
655
1578
|
return;
|
|
@@ -659,11 +1582,11 @@ function readExisting(path) {
|
|
|
659
1582
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
660
1583
|
throw new Error("stored client instance identity is invalid");
|
|
661
1584
|
}
|
|
662
|
-
|
|
1585
|
+
chmodSync2(path, INSTANCE_FILE_MODE);
|
|
663
1586
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
664
1587
|
throw new Error("stored client instance identity is invalid");
|
|
665
1588
|
}
|
|
666
|
-
const raw =
|
|
1589
|
+
const raw = readFileSync7(path, "utf8");
|
|
667
1590
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
668
1591
|
if (raw !== value && raw !== `${value}
|
|
669
1592
|
` || !isClientInstanceId(value)) {
|
|
@@ -677,8 +1600,8 @@ function atomicWrite(path, value) {
|
|
|
677
1600
|
}
|
|
678
1601
|
async function getOrCreateClientInstanceId(options) {
|
|
679
1602
|
const configDir = options.configDir;
|
|
680
|
-
const path =
|
|
681
|
-
const lockPath =
|
|
1603
|
+
const path = join8(configDir, "client_instance_id");
|
|
1604
|
+
const lockPath = join8(configDir, "client-instance.lock");
|
|
682
1605
|
ensurePrivateConfigDirectory(configDir);
|
|
683
1606
|
return withFileLock(
|
|
684
1607
|
lockPath,
|
|
@@ -687,7 +1610,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
687
1610
|
if (existing !== void 0) {
|
|
688
1611
|
return existing;
|
|
689
1612
|
}
|
|
690
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
1613
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes3(INSTANCE_ENTROPY_BYTES).toString(
|
|
691
1614
|
"base64url"
|
|
692
1615
|
)}`;
|
|
693
1616
|
if (!isClientInstanceId(generated)) {
|
|
@@ -700,50 +1623,6 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
700
1623
|
);
|
|
701
1624
|
}
|
|
702
1625
|
|
|
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
1626
|
// src/lib/ingest-uploader.ts
|
|
748
1627
|
var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
|
|
749
1628
|
var VERSION_RE = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/u;
|
|
@@ -811,11 +1690,11 @@ function terminalSafeLine(value) {
|
|
|
811
1690
|
var CONFIG_DIR_MODE = 448;
|
|
812
1691
|
var CREDENTIAL_FILE_MODE = 384;
|
|
813
1692
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
814
|
-
var
|
|
1693
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
815
1694
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
816
1695
|
function readTrimmed2(path) {
|
|
817
1696
|
try {
|
|
818
|
-
const value =
|
|
1697
|
+
const value = readFileSync8(path, "utf8").trim();
|
|
819
1698
|
return value || void 0;
|
|
820
1699
|
} catch {
|
|
821
1700
|
return void 0;
|
|
@@ -825,26 +1704,27 @@ function getSiteUrl() {
|
|
|
825
1704
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
826
1705
|
}
|
|
827
1706
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
828
|
-
return primApiUrl?.trim() ||
|
|
1707
|
+
return primApiUrl?.trim() || DEFAULT_API_URL2;
|
|
829
1708
|
}
|
|
830
1709
|
function expiresAtFor(token, expiresIn) {
|
|
831
1710
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
832
1711
|
}
|
|
833
1712
|
function ensureConfigDirectory() {
|
|
834
|
-
const directory =
|
|
835
|
-
|
|
836
|
-
|
|
1713
|
+
const directory = dirname5(TOKEN_FILE_PATH);
|
|
1714
|
+
mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
1715
|
+
chmodSync3(directory, CONFIG_DIR_MODE);
|
|
837
1716
|
}
|
|
838
1717
|
function atomicWrite2(path, content) {
|
|
839
1718
|
ensureConfigDirectory();
|
|
840
1719
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
841
1720
|
}
|
|
842
1721
|
function removeCredentialFile(path) {
|
|
843
|
-
if (!
|
|
844
|
-
|
|
1722
|
+
if (!existsSync4(path)) return false;
|
|
1723
|
+
rmSync6(path, { force: true });
|
|
845
1724
|
return true;
|
|
846
1725
|
}
|
|
847
1726
|
function getTokenExpiresAt() {
|
|
1727
|
+
if (hasMachineConfiguration()) return cachedMachineCredential()?.expiresAt;
|
|
848
1728
|
const stored = readTrimmed2(TOKEN_EXPIRES_PATH);
|
|
849
1729
|
if (stored === void 0) return void 0;
|
|
850
1730
|
const value = Number(stored);
|
|
@@ -856,7 +1736,7 @@ function isTokenExpiringSoon(credential) {
|
|
|
856
1736
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
857
1737
|
}
|
|
858
1738
|
function refreshFingerprint(refreshToken2) {
|
|
859
|
-
return
|
|
1739
|
+
return createHash5("sha256").update(refreshToken2).digest("hex");
|
|
860
1740
|
}
|
|
861
1741
|
function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
|
|
862
1742
|
return {
|
|
@@ -921,6 +1801,7 @@ function clearTerminalFingerprint() {
|
|
|
921
1801
|
removeCredentialFile(TERMINAL_REFRESH_PATH);
|
|
922
1802
|
}
|
|
923
1803
|
function isSessionEnded() {
|
|
1804
|
+
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
924
1805
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
925
1806
|
const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
926
1807
|
const ended = terminalFingerprint();
|
|
@@ -1161,6 +2042,8 @@ async function performTokenRefresh(options = {}) {
|
|
|
1161
2042
|
}
|
|
1162
2043
|
var _refreshInFlight;
|
|
1163
2044
|
function refreshToken(options = {}) {
|
|
2045
|
+
if (hasMachineConfiguration())
|
|
2046
|
+
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
1164
2047
|
if (_refreshInFlight) return _refreshInFlight;
|
|
1165
2048
|
const attempt = performTokenRefresh(options).then((token) => {
|
|
1166
2049
|
if (token) _cachedCredential = { token, source: "token_file" };
|
|
@@ -1181,7 +2064,29 @@ var HttpError = class extends Error {
|
|
|
1181
2064
|
this.body = body;
|
|
1182
2065
|
}
|
|
1183
2066
|
};
|
|
2067
|
+
var CliManagementResponseError = class extends Error {
|
|
2068
|
+
constructor() {
|
|
2069
|
+
super("Invalid API-key management response");
|
|
2070
|
+
this.name = "CliManagementResponseError";
|
|
2071
|
+
}
|
|
2072
|
+
};
|
|
1184
2073
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
2074
|
+
async function managementResponseValue(response) {
|
|
2075
|
+
if (response.status === 401) {
|
|
2076
|
+
throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
|
|
2077
|
+
}
|
|
2078
|
+
let value;
|
|
2079
|
+
try {
|
|
2080
|
+
value = await readBoundedJson(response, CLI_MANAGEMENT_RESPONSE_MAX_BYTES);
|
|
2081
|
+
} catch {
|
|
2082
|
+
if (response.ok) throw new CliManagementResponseError();
|
|
2083
|
+
throw new HttpError(response.status, `HTTP ${response.status}`, null);
|
|
2084
|
+
}
|
|
2085
|
+
if (!response.ok) {
|
|
2086
|
+
throw new HttpError(response.status, `HTTP ${response.status}`, value);
|
|
2087
|
+
}
|
|
2088
|
+
return value;
|
|
2089
|
+
}
|
|
1185
2090
|
var _cachedCredential;
|
|
1186
2091
|
function selectedCredential() {
|
|
1187
2092
|
const resolved = resolveAuthCredential();
|
|
@@ -1199,7 +2104,8 @@ async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
|
1199
2104
|
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
1200
2105
|
},
|
|
1201
2106
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
1202
|
-
signal: options?.signal
|
|
2107
|
+
signal: options?.signal,
|
|
2108
|
+
redirect: options?.redirect
|
|
1203
2109
|
});
|
|
1204
2110
|
}
|
|
1205
2111
|
async function responseValue(response) {
|
|
@@ -1214,7 +2120,66 @@ async function responseValue(response) {
|
|
|
1214
2120
|
}
|
|
1215
2121
|
return publicDecisionResponse(await response.json());
|
|
1216
2122
|
}
|
|
2123
|
+
async function machineClient(options = {}, management = false) {
|
|
2124
|
+
let credential;
|
|
2125
|
+
try {
|
|
2126
|
+
credential = await acquireMachineCredential(options);
|
|
2127
|
+
} catch (error) {
|
|
2128
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
2129
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
2130
|
+
}
|
|
2131
|
+
if (!credential) return void 0;
|
|
2132
|
+
const selected = credential;
|
|
2133
|
+
const parse = management ? managementResponseValue : responseValue;
|
|
2134
|
+
const send = async (method, path, body, requestOptions = {}) => {
|
|
2135
|
+
if (machineContext()?.generation !== selected.generation) {
|
|
2136
|
+
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2137
|
+
}
|
|
2138
|
+
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
2139
|
+
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.organizationId !== selected.organizationId)
|
|
2140
|
+
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2141
|
+
let response = await fetchWithToken(
|
|
2142
|
+
method,
|
|
2143
|
+
path,
|
|
2144
|
+
body,
|
|
2145
|
+
{ ...requestOptions, redirect: "error" },
|
|
2146
|
+
current.accessToken,
|
|
2147
|
+
selected.apiUrl
|
|
2148
|
+
);
|
|
2149
|
+
if (response.status === 401) {
|
|
2150
|
+
const renewed = await acquireMachineCredential({
|
|
2151
|
+
force: true,
|
|
2152
|
+
signal: requestOptions.signal
|
|
2153
|
+
});
|
|
2154
|
+
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.organizationId !== selected.organizationId) {
|
|
2155
|
+
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2156
|
+
}
|
|
2157
|
+
response = await fetchWithToken(
|
|
2158
|
+
method,
|
|
2159
|
+
path,
|
|
2160
|
+
body,
|
|
2161
|
+
{ ...requestOptions, redirect: "error" },
|
|
2162
|
+
renewed.accessToken,
|
|
2163
|
+
renewed.apiUrl
|
|
2164
|
+
);
|
|
2165
|
+
}
|
|
2166
|
+
if (response.status === 401)
|
|
2167
|
+
throw new HttpError(
|
|
2168
|
+
401,
|
|
2169
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2170
|
+
);
|
|
2171
|
+
return parse(response);
|
|
2172
|
+
};
|
|
2173
|
+
return {
|
|
2174
|
+
get: (path, opts) => send("GET", path, void 0, opts),
|
|
2175
|
+
post: (path, body, opts) => send("POST", path, body, opts),
|
|
2176
|
+
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
1217
2179
|
async function request(method, path, body, options) {
|
|
2180
|
+
const machine = await machineClient(options);
|
|
2181
|
+
if (machine)
|
|
2182
|
+
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
1218
2183
|
const siteUrl = getSiteUrl();
|
|
1219
2184
|
let credential = selectedCredential();
|
|
1220
2185
|
let refreshAttempted = false;
|
|
@@ -1259,15 +2224,23 @@ function getClient() {
|
|
|
1259
2224
|
}
|
|
1260
2225
|
|
|
1261
2226
|
// src/daemon/principal.ts
|
|
1262
|
-
import { createHash as
|
|
2227
|
+
import { createHash as createHash6 } from "crypto";
|
|
1263
2228
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
1264
2229
|
function boundedClaim(value) {
|
|
1265
2230
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
1266
2231
|
}
|
|
1267
2232
|
function sha256(value) {
|
|
1268
|
-
return
|
|
2233
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
1269
2234
|
}
|
|
1270
2235
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
2236
|
+
if (hasMachineConfiguration()) {
|
|
2237
|
+
const machine = machineContext();
|
|
2238
|
+
return machine ? {
|
|
2239
|
+
principalId: sha256(`${machine.issuer}\0${machine.clientId}`),
|
|
2240
|
+
organizationId: machine.workosOrganizationId,
|
|
2241
|
+
credentialFingerprint: sha256(machine.generation)
|
|
2242
|
+
} : void 0;
|
|
2243
|
+
}
|
|
1271
2244
|
if (!token) return void 0;
|
|
1272
2245
|
const payload = decodeJwtPayload(token);
|
|
1273
2246
|
const subject = boundedClaim(payload?.sub);
|
|
@@ -1306,8 +2279,8 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
1306
2279
|
|
|
1307
2280
|
// src/daemon/client.ts
|
|
1308
2281
|
import { createConnection } from "net";
|
|
1309
|
-
import { join as
|
|
1310
|
-
var SOCK_PATH =
|
|
2282
|
+
import { join as join10 } from "path";
|
|
2283
|
+
var SOCK_PATH = join10(primConfigDirectory(), "sock");
|
|
1311
2284
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
1312
2285
|
var nextRequestId = 1;
|
|
1313
2286
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -1421,26 +2394,26 @@ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_T
|
|
|
1421
2394
|
}
|
|
1422
2395
|
|
|
1423
2396
|
// src/lib/activation.ts
|
|
1424
|
-
import { execFileSync as
|
|
1425
|
-
import { existsSync as
|
|
2397
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
2398
|
+
import { existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
|
|
1426
2399
|
import { homedir as homedir2 } from "os";
|
|
1427
|
-
import { join as
|
|
2400
|
+
import { join as join11 } from "path";
|
|
1428
2401
|
|
|
1429
2402
|
// src/lib/demo-pause.ts
|
|
1430
|
-
import { execFileSync } from "child_process";
|
|
2403
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
1431
2404
|
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
1432
2405
|
|
|
1433
2406
|
// src/lib/git.ts
|
|
1434
|
-
import { execFileSync as
|
|
1435
|
-
import { createHash as
|
|
1436
|
-
import { lstatSync as
|
|
1437
|
-
import { basename, dirname as
|
|
2407
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
2408
|
+
import { createHash as createHash7 } from "crypto";
|
|
2409
|
+
import { lstatSync as lstatSync5, realpathSync } from "fs";
|
|
2410
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
|
|
1438
2411
|
var GIT_TIMEOUT_MS = 1e3;
|
|
1439
2412
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
1440
2413
|
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
1441
2414
|
function gitToplevel(cwd) {
|
|
1442
2415
|
try {
|
|
1443
|
-
return
|
|
2416
|
+
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
1444
2417
|
cwd,
|
|
1445
2418
|
encoding: "utf-8",
|
|
1446
2419
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -1452,7 +2425,7 @@ function gitToplevel(cwd) {
|
|
|
1452
2425
|
}
|
|
1453
2426
|
function gitValue(cwd, args) {
|
|
1454
2427
|
try {
|
|
1455
|
-
const value =
|
|
2428
|
+
const value = execFileSync3("git", args, {
|
|
1456
2429
|
cwd,
|
|
1457
2430
|
encoding: "utf-8",
|
|
1458
2431
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -1493,12 +2466,12 @@ function nearestExistingAncestor(path) {
|
|
|
1493
2466
|
let cursor = path;
|
|
1494
2467
|
while (true) {
|
|
1495
2468
|
try {
|
|
1496
|
-
|
|
2469
|
+
lstatSync5(cursor);
|
|
1497
2470
|
break;
|
|
1498
2471
|
} catch (error) {
|
|
1499
2472
|
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
1500
2473
|
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
1501
|
-
const parent =
|
|
2474
|
+
const parent = dirname6(cursor);
|
|
1502
2475
|
if (parent === cursor) return null;
|
|
1503
2476
|
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
1504
2477
|
cursor = parent;
|
|
@@ -1531,7 +2504,7 @@ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonical
|
|
|
1531
2504
|
const absolute = resolve2(cwd, filePath);
|
|
1532
2505
|
let target;
|
|
1533
2506
|
try {
|
|
1534
|
-
const stat =
|
|
2507
|
+
const stat = lstatSync5(absolute);
|
|
1535
2508
|
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
1536
2509
|
target = realpathSync.native(absolute);
|
|
1537
2510
|
} catch (error) {
|
|
@@ -1539,9 +2512,9 @@ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonical
|
|
|
1539
2512
|
return null;
|
|
1540
2513
|
}
|
|
1541
2514
|
try {
|
|
1542
|
-
const parent = realpathSync.native(
|
|
1543
|
-
if (!
|
|
1544
|
-
target = resolve2(parent,
|
|
2515
|
+
const parent = realpathSync.native(dirname6(absolute));
|
|
2516
|
+
if (!lstatSync5(parent).isDirectory()) return null;
|
|
2517
|
+
target = resolve2(parent, basename2(absolute));
|
|
1545
2518
|
} catch {
|
|
1546
2519
|
return null;
|
|
1547
2520
|
}
|
|
@@ -1573,7 +2546,7 @@ function isValidRepoSyncId(value) {
|
|
|
1573
2546
|
}
|
|
1574
2547
|
function localGitConfigValue(cwd, key) {
|
|
1575
2548
|
try {
|
|
1576
|
-
const value =
|
|
2549
|
+
const value = execFileSync4("git", ["config", "--local", "--get", key], {
|
|
1577
2550
|
cwd,
|
|
1578
2551
|
encoding: "utf-8",
|
|
1579
2552
|
stdio: ["ignore", "pipe", "ignore"],
|