@primitive.ai/prim 0.1.0-alpha.126 → 0.1.0-alpha.128
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 +211 -1
- package/SKILL.md +6 -1
- package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
- package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
- package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
- package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
- package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
- package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
- package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
- package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
- package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
- package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
- package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
- package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
- package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
- package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
- package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
- package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
- package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
- package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
- package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
- package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
- package/dist/daemon/server.js +1976 -442
- package/dist/hook-runtime/daemon/server.js +1976 -442
- package/dist/hook-runtime/hooks/post-commit.js +592 -212
- package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
- package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
- package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
- package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
- package/dist/hook-runtime/hooks/session-end.js +549 -180
- package/dist/hook-runtime/hooks/session-start.js +2213 -596
- package/dist/hook-runtime/index.js +5318 -2423
- package/dist/hook-runtime/statusline-main.js +531 -150
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +18 -18
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +14 -15
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +95 -21
- package/dist/index.js +1386 -299
- package/dist/statusline-main.js +531 -150
- package/package.json +1 -1
|
@@ -116,6 +116,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
|
116
116
|
'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; ',
|
|
117
117
|
"fi; fi; "
|
|
118
118
|
].join("");
|
|
119
|
+
var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
|
|
119
120
|
function stableHookCommand(bin, args = "") {
|
|
120
121
|
if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
|
|
121
122
|
throw new Error("invalid stable hook command");
|
|
@@ -127,7 +128,7 @@ function stableHookCommand(bin, args = "") {
|
|
|
127
128
|
`prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
|
|
128
129
|
PRIM_CONFIG_SHELL_RESOLVER,
|
|
129
130
|
`case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
|
|
130
|
-
|
|
131
|
+
LAUNCHER_EXEC
|
|
131
132
|
].join("");
|
|
132
133
|
const suffix = args ? ` ${args}` : "";
|
|
133
134
|
return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
|
|
@@ -27402,10 +27403,27 @@ function observeDemoInvocation(envelope, agent2, checkExclusion = true) {
|
|
|
27402
27403
|
|
|
27403
27404
|
// src/lib/activation.ts
|
|
27404
27405
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
27405
|
-
import { existsSync as
|
|
27406
|
+
import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
|
|
27406
27407
|
import { homedir as homedir2 } from "os";
|
|
27408
|
+
import { join as join10 } from "path";
|
|
27409
|
+
|
|
27410
|
+
// src/lib/cloud-prepared.ts
|
|
27411
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
|
|
27407
27412
|
import { join as join8 } from "path";
|
|
27408
27413
|
|
|
27414
|
+
// src/lib/cloud-env.ts
|
|
27415
|
+
function isClaudeCloudSession(env = process.env) {
|
|
27416
|
+
return env.CLAUDE_CODE_REMOTE === "true";
|
|
27417
|
+
}
|
|
27418
|
+
var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
|
|
27419
|
+
var CLOUD_REJECTED_CREDENTIALS_REMEDY = 'correct the credentials in the cloud environment\'s settings, or if the installation was revoked mint a replacement on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`; then start a new cloud session';
|
|
27420
|
+
var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
|
|
27421
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
27422
|
+
function cloudSetupPointer(message, env = process.env) {
|
|
27423
|
+
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
27424
|
+
}
|
|
27425
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
27426
|
+
|
|
27409
27427
|
// src/lib/demo-pause.ts
|
|
27410
27428
|
import { execFileSync } from "child_process";
|
|
27411
27429
|
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
@@ -27413,18 +27431,26 @@ var DEMO_PAUSE_MS = 30 * 6e4;
|
|
|
27413
27431
|
// src/lib/git.ts
|
|
27414
27432
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
27415
27433
|
import { createHash as createHash3 } from "crypto";
|
|
27416
|
-
import { lstatSync as lstatSync3, realpathSync as realpathSync2 } from "fs";
|
|
27417
|
-
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, relative, resolve as resolve3, sep } from "path";
|
|
27434
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
|
|
27435
|
+
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join9, relative, resolve as resolve3, sep } from "path";
|
|
27418
27436
|
var GIT_TIMEOUT_MS = 1e3;
|
|
27437
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
27419
27438
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
27420
|
-
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
27439
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
27440
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
27441
|
+
function gitChildEnvironment(env = process.env) {
|
|
27442
|
+
return Object.fromEntries(
|
|
27443
|
+
Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
|
|
27444
|
+
);
|
|
27445
|
+
}
|
|
27421
27446
|
function gitToplevel(cwd) {
|
|
27422
27447
|
try {
|
|
27423
27448
|
return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
|
|
27424
27449
|
cwd,
|
|
27425
27450
|
encoding: "utf-8",
|
|
27426
27451
|
stdio: ["ignore", "pipe", "ignore"],
|
|
27427
|
-
timeout: GIT_TIMEOUT_MS
|
|
27452
|
+
timeout: GIT_TIMEOUT_MS,
|
|
27453
|
+
env: gitChildEnvironment()
|
|
27428
27454
|
}).trim();
|
|
27429
27455
|
} catch {
|
|
27430
27456
|
return null;
|
|
@@ -27436,7 +27462,8 @@ function gitValue(cwd, args) {
|
|
|
27436
27462
|
cwd,
|
|
27437
27463
|
encoding: "utf-8",
|
|
27438
27464
|
stdio: ["ignore", "pipe", "ignore"],
|
|
27439
|
-
timeout: GIT_TIMEOUT_MS
|
|
27465
|
+
timeout: GIT_TIMEOUT_MS,
|
|
27466
|
+
env: gitChildEnvironment()
|
|
27440
27467
|
}).trim();
|
|
27441
27468
|
return value || void 0;
|
|
27442
27469
|
} catch {
|
|
@@ -27446,19 +27473,57 @@ function gitValue(cwd, args) {
|
|
|
27446
27473
|
function currentBranch(cwd) {
|
|
27447
27474
|
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
27448
27475
|
}
|
|
27449
|
-
function
|
|
27450
|
-
const
|
|
27451
|
-
if (
|
|
27476
|
+
function parseGithubRepositoryName(path) {
|
|
27477
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
27478
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
27479
|
+
return null;
|
|
27480
|
+
}
|
|
27481
|
+
return `${parts[0]}/${parts[1]}`;
|
|
27482
|
+
}
|
|
27483
|
+
function githubRepositoryFromRemote(remote) {
|
|
27484
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
27452
27485
|
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
27453
27486
|
remote
|
|
27454
27487
|
);
|
|
27455
27488
|
const path = match?.[1] ?? match?.[2];
|
|
27456
|
-
|
|
27457
|
-
|
|
27458
|
-
|
|
27489
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
27490
|
+
}
|
|
27491
|
+
function checkoutSettingsText(repoRoot) {
|
|
27492
|
+
const path = join9(repoRoot, ".claude", "settings.json");
|
|
27493
|
+
try {
|
|
27494
|
+
if (!lstatSync3(join9(repoRoot, ".claude")).isDirectory()) return null;
|
|
27495
|
+
const stat = lstatSync3(path);
|
|
27496
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
27497
|
+
return readFileSync6(path, "utf8");
|
|
27498
|
+
} catch {
|
|
27459
27499
|
return null;
|
|
27460
27500
|
}
|
|
27461
|
-
|
|
27501
|
+
}
|
|
27502
|
+
function checkoutDeclaration(repoRoot, name2) {
|
|
27503
|
+
const text = checkoutSettingsText(repoRoot);
|
|
27504
|
+
if (text === null) return null;
|
|
27505
|
+
let parsed;
|
|
27506
|
+
try {
|
|
27507
|
+
parsed = JSON.parse(text);
|
|
27508
|
+
} catch {
|
|
27509
|
+
return null;
|
|
27510
|
+
}
|
|
27511
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
27512
|
+
const value = typeof env === "object" && env !== null ? env[name2] : void 0;
|
|
27513
|
+
return typeof value === "string" ? value : null;
|
|
27514
|
+
}
|
|
27515
|
+
function declaredGithubRepository(repoRoot) {
|
|
27516
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
27517
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
27518
|
+
}
|
|
27519
|
+
function githubRepositoryFullName(cwd) {
|
|
27520
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
27521
|
+
if (remote) {
|
|
27522
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
27523
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
27524
|
+
}
|
|
27525
|
+
const root = gitToplevel(cwd);
|
|
27526
|
+
return root ? declaredGithubRepository(root) : null;
|
|
27462
27527
|
}
|
|
27463
27528
|
function canonicalGitRoot(cwd) {
|
|
27464
27529
|
try {
|
|
@@ -27512,6 +27577,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
|
|
|
27512
27577
|
repoFullName
|
|
27513
27578
|
};
|
|
27514
27579
|
}
|
|
27580
|
+
if (repoFullName) {
|
|
27581
|
+
return {
|
|
27582
|
+
repoRoot,
|
|
27583
|
+
repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
|
|
27584
|
+
identitySource: "declared",
|
|
27585
|
+
repoFullName
|
|
27586
|
+
};
|
|
27587
|
+
}
|
|
27515
27588
|
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
27516
27589
|
if (roots && roots.length > 0) {
|
|
27517
27590
|
return {
|
|
@@ -27723,31 +27796,70 @@ function publicDecisionResponse(value) {
|
|
|
27723
27796
|
}
|
|
27724
27797
|
|
|
27725
27798
|
// src/client.ts
|
|
27726
|
-
import { createHash as
|
|
27727
|
-
import { chmodSync as chmodSync4, existsSync as
|
|
27799
|
+
import { createHash as createHash9 } from "crypto";
|
|
27800
|
+
import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync9 } from "fs";
|
|
27728
27801
|
import { dirname as dirname8 } from "path";
|
|
27729
27802
|
|
|
27730
27803
|
// src/lib/credentials.ts
|
|
27731
|
-
import { createHash as
|
|
27732
|
-
import { readFileSync as
|
|
27733
|
-
import { join as
|
|
27804
|
+
import { createHash as createHash8 } from "crypto";
|
|
27805
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
27806
|
+
import { join as join15 } from "path";
|
|
27734
27807
|
|
|
27735
27808
|
// src/lib/machine-credentials.ts
|
|
27736
27809
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
27737
|
-
import { createHash as
|
|
27738
|
-
import {
|
|
27810
|
+
import { createHash as createHash7, randomBytes as randomBytes4, randomUUID as randomUUID3 } from "crypto";
|
|
27811
|
+
import {
|
|
27812
|
+
chmodSync as chmodSync2,
|
|
27813
|
+
existsSync as existsSync10,
|
|
27814
|
+
linkSync,
|
|
27815
|
+
lstatSync as lstatSync6,
|
|
27816
|
+
mkdirSync as mkdirSync5,
|
|
27817
|
+
readFileSync as readFileSync10,
|
|
27818
|
+
rmSync as rmSync8,
|
|
27819
|
+
writeFileSync as writeFileSync5
|
|
27820
|
+
} from "fs";
|
|
27739
27821
|
import { createRequire as createRequire2 } from "module";
|
|
27740
|
-
import { dirname as dirname7, join as
|
|
27822
|
+
import { dirname as dirname7, join as join14 } from "path";
|
|
27741
27823
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
27742
27824
|
|
|
27743
27825
|
// src/lib/machine-broker.ts
|
|
27744
27826
|
import { spawn } from "child_process";
|
|
27745
27827
|
import { createHash as createHash4, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
27746
|
-
import { lstatSync as lstatSync4, readFileSync as
|
|
27828
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync8, rmSync as rmSync5 } from "fs";
|
|
27747
27829
|
import { createServer } from "http";
|
|
27748
|
-
import { basename as basename2, join as
|
|
27830
|
+
import { basename as basename2, join as join11 } from "path";
|
|
27749
27831
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
27750
27832
|
|
|
27833
|
+
// src/lib/loopback-fetch.ts
|
|
27834
|
+
import { request } from "http";
|
|
27835
|
+
import { Readable } from "stream";
|
|
27836
|
+
function loopbackFetch(url, init = {}) {
|
|
27837
|
+
const target = new URL(url);
|
|
27838
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
27839
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
27840
|
+
return new Promise((resolve7, reject) => {
|
|
27841
|
+
const outgoing = request(
|
|
27842
|
+
target,
|
|
27843
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
27844
|
+
(incoming) => {
|
|
27845
|
+
try {
|
|
27846
|
+
const headers = new Headers();
|
|
27847
|
+
for (const [name2, value] of Object.entries(incoming.headers))
|
|
27848
|
+
if (typeof value === "string") headers.set(name2, value);
|
|
27849
|
+
const status = incoming.statusCode ?? 502;
|
|
27850
|
+
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
27851
|
+
resolve7(new Response(body, { status, headers }));
|
|
27852
|
+
} catch (error) {
|
|
27853
|
+
incoming.destroy();
|
|
27854
|
+
reject(error);
|
|
27855
|
+
}
|
|
27856
|
+
}
|
|
27857
|
+
);
|
|
27858
|
+
outgoing.once("error", reject);
|
|
27859
|
+
outgoing.end(init.body);
|
|
27860
|
+
});
|
|
27861
|
+
}
|
|
27862
|
+
|
|
27751
27863
|
// src/lib/workos-connect.ts
|
|
27752
27864
|
var TOKEN_PATH = "/oauth2/token";
|
|
27753
27865
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -27884,10 +27996,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
27884
27996
|
"access_token",
|
|
27885
27997
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
27886
27998
|
);
|
|
27887
|
-
const
|
|
27999
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
27888
28000
|
return {
|
|
27889
28001
|
accessToken,
|
|
27890
|
-
refreshToken:
|
|
28002
|
+
refreshToken: refreshToken3,
|
|
27891
28003
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
27892
28004
|
};
|
|
27893
28005
|
}
|
|
@@ -27943,9 +28055,19 @@ function parseMachineConfiguration(value) {
|
|
|
27943
28055
|
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
27944
28056
|
};
|
|
27945
28057
|
}
|
|
28058
|
+
function rejectedCredentialsMessage(message, env = process.env) {
|
|
28059
|
+
return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
28060
|
+
}
|
|
27946
28061
|
function machineSignal(signal) {
|
|
27947
28062
|
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
27948
28063
|
}
|
|
28064
|
+
function hostOf(url) {
|
|
28065
|
+
try {
|
|
28066
|
+
return new URL(url).hostname;
|
|
28067
|
+
} catch {
|
|
28068
|
+
return "Primitive";
|
|
28069
|
+
}
|
|
28070
|
+
}
|
|
27949
28071
|
async function fetchMachine(url, options, fetchImpl) {
|
|
27950
28072
|
try {
|
|
27951
28073
|
return await fetchImpl(url, options);
|
|
@@ -27953,7 +28075,9 @@ async function fetchMachine(url, options, fetchImpl) {
|
|
|
27953
28075
|
options.signal?.throwIfAborted();
|
|
27954
28076
|
throw new MachineAuthError(
|
|
27955
28077
|
"authentication_unavailable",
|
|
27956
|
-
|
|
28078
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
28079
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
28080
|
+
isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
27957
28081
|
);
|
|
27958
28082
|
}
|
|
27959
28083
|
}
|
|
@@ -27980,8 +28104,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
|
27980
28104
|
);
|
|
27981
28105
|
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
27982
28106
|
}
|
|
27983
|
-
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
27984
|
-
|
|
28107
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
28108
|
+
const network = options.secretInjection === "network";
|
|
28109
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
27985
28110
|
throw new MachineAuthError(
|
|
27986
28111
|
"invalid_credentials",
|
|
27987
28112
|
"A machine client ID and secret are required.",
|
|
@@ -27995,11 +28120,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
27995
28120
|
redirect: "error",
|
|
27996
28121
|
signal: machineSignal(signal),
|
|
27997
28122
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
27998
|
-
|
|
27999
|
-
|
|
28000
|
-
|
|
28001
|
-
client_secret: clientSecret
|
|
28002
|
-
|
|
28123
|
+
// With a network secret the agent proxy authenticates the client with
|
|
28124
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
28125
|
+
body: new URLSearchParams(
|
|
28126
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
28127
|
+
)
|
|
28003
28128
|
},
|
|
28004
28129
|
fetchImpl
|
|
28005
28130
|
);
|
|
@@ -28007,7 +28132,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
28007
28132
|
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
28008
28133
|
throw new MachineAuthError(
|
|
28009
28134
|
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
28010
|
-
terminal ?
|
|
28135
|
+
terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
|
|
28136
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
28137
|
+
) : "The machine token service is temporarily unavailable.",
|
|
28011
28138
|
terminal,
|
|
28012
28139
|
terminal ? void 0 : machineRetryAt(response)
|
|
28013
28140
|
);
|
|
@@ -28027,6 +28154,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
28027
28154
|
} catch {
|
|
28028
28155
|
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
28029
28156
|
}
|
|
28157
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
28158
|
+
throw new MachineAuthError(
|
|
28159
|
+
"token_client_mismatch",
|
|
28160
|
+
"The token service issued a token for another machine client."
|
|
28161
|
+
);
|
|
28030
28162
|
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()) {
|
|
28031
28163
|
throw new MachineAuthError(
|
|
28032
28164
|
"token_identity_mismatch",
|
|
@@ -28072,32 +28204,76 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
|
|
|
28072
28204
|
const terminal = response.status === 401 || response.status === 403;
|
|
28073
28205
|
throw new MachineAuthError(
|
|
28074
28206
|
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
28075
|
-
terminal ?
|
|
28207
|
+
terminal ? rejectedCredentialsMessage(
|
|
28208
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
28209
|
+
) : "Machine verification is temporarily unavailable.",
|
|
28076
28210
|
terminal
|
|
28077
28211
|
);
|
|
28078
28212
|
}
|
|
28079
28213
|
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
28080
28214
|
}
|
|
28215
|
+
function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
|
|
28216
|
+
const rejected = () => new MachineAuthError(
|
|
28217
|
+
"network_token_rejected",
|
|
28218
|
+
`Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
|
|
28219
|
+
true
|
|
28220
|
+
);
|
|
28221
|
+
if (status === 401 || status === 403) throw rejected();
|
|
28222
|
+
if (status < 200 || status > 299)
|
|
28223
|
+
throw new MachineAuthError(
|
|
28224
|
+
"verification_unavailable",
|
|
28225
|
+
"Machine verification is temporarily unavailable."
|
|
28226
|
+
);
|
|
28227
|
+
let data;
|
|
28228
|
+
try {
|
|
28229
|
+
data = machineRecord(value);
|
|
28230
|
+
} catch {
|
|
28231
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
28232
|
+
}
|
|
28233
|
+
if (data.authenticated !== true) throw rejected();
|
|
28234
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
28235
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
28236
|
+
throw new MachineAuthError(
|
|
28237
|
+
"network_secret_mismatch",
|
|
28238
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
28239
|
+
true
|
|
28240
|
+
);
|
|
28241
|
+
return parseMachineIdentity(data, clientId);
|
|
28242
|
+
}
|
|
28243
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
28244
|
+
const response = await fetchMachine(
|
|
28245
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
28246
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
28247
|
+
fetchImpl
|
|
28248
|
+
);
|
|
28249
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
28250
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
28251
|
+
}
|
|
28081
28252
|
|
|
28082
28253
|
// src/lib/machine-broker.ts
|
|
28083
28254
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
28255
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
28256
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
28257
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
28258
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
28259
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
28084
28260
|
var IDLE_MS = 5 * 6e4;
|
|
28085
28261
|
function descriptorPath(directory, generation) {
|
|
28086
|
-
return
|
|
28262
|
+
return join11(directory, `machine_broker_${generation}.json`);
|
|
28087
28263
|
}
|
|
28088
28264
|
function readDescriptor(path) {
|
|
28089
28265
|
try {
|
|
28090
28266
|
const stat = lstatSync4(path);
|
|
28091
28267
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
28092
28268
|
return void 0;
|
|
28093
|
-
const data = JSON.parse(
|
|
28269
|
+
const data = JSON.parse(readFileSync8(path, "utf8"));
|
|
28094
28270
|
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;
|
|
28095
28271
|
} catch {
|
|
28096
28272
|
return void 0;
|
|
28097
28273
|
}
|
|
28098
28274
|
}
|
|
28099
|
-
function signature(secret, nonce, body) {
|
|
28100
|
-
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
28275
|
+
function signature(secret, nonce, body, purpose) {
|
|
28276
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
28101
28277
|
}
|
|
28102
28278
|
function matches(left, right) {
|
|
28103
28279
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
@@ -28112,10 +28288,9 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
28112
28288
|
observedTokenHash: tokenHash(options.observedToken),
|
|
28113
28289
|
timestamp: Date.now()
|
|
28114
28290
|
});
|
|
28115
|
-
const response = await
|
|
28291
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
28116
28292
|
method: "POST",
|
|
28117
28293
|
body,
|
|
28118
|
-
redirect: "error",
|
|
28119
28294
|
signal: options.signal,
|
|
28120
28295
|
headers: {
|
|
28121
28296
|
"Content-Type": "application/json",
|
|
@@ -28146,6 +28321,15 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
28146
28321
|
);
|
|
28147
28322
|
return credential;
|
|
28148
28323
|
}
|
|
28324
|
+
function brokerEnvironment(options) {
|
|
28325
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
28326
|
+
return {
|
|
28327
|
+
...options.env,
|
|
28328
|
+
PRIM_API_URL: options.apiUrl,
|
|
28329
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
28330
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
28331
|
+
};
|
|
28332
|
+
}
|
|
28149
28333
|
async function acquireBrokerCredential(options) {
|
|
28150
28334
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
28151
28335
|
const existing = readDescriptor(path);
|
|
@@ -28157,15 +28341,28 @@ async function acquireBrokerCredential(options) {
|
|
|
28157
28341
|
if (error instanceof MachineAuthError) throw error;
|
|
28158
28342
|
}
|
|
28159
28343
|
}
|
|
28160
|
-
const descriptor = await
|
|
28161
|
-
|
|
28344
|
+
const descriptor = await ensureBroker(options);
|
|
28345
|
+
try {
|
|
28346
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
28347
|
+
} catch (error) {
|
|
28348
|
+
options.signal.throwIfAborted();
|
|
28349
|
+
if (error instanceof MachineAuthError) throw error;
|
|
28350
|
+
throw new MachineAuthError(
|
|
28351
|
+
"broker_unavailable",
|
|
28352
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
28353
|
+
);
|
|
28354
|
+
}
|
|
28355
|
+
}
|
|
28356
|
+
async function ensureBroker(options) {
|
|
28357
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
28358
|
+
return withFileLock(
|
|
28359
|
+
join11(options.directory, "machine-broker.lock"),
|
|
28162
28360
|
async () => {
|
|
28163
28361
|
const current = readDescriptor(path);
|
|
28164
28362
|
if (current) {
|
|
28165
28363
|
try {
|
|
28166
|
-
const response = await
|
|
28167
|
-
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
28168
|
-
redirect: "error"
|
|
28364
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
28365
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
28169
28366
|
});
|
|
28170
28367
|
if (response.ok && await response.text() === current.nonce) return current;
|
|
28171
28368
|
} catch {
|
|
@@ -28184,7 +28381,7 @@ async function acquireBrokerCredential(options) {
|
|
|
28184
28381
|
detached: true,
|
|
28185
28382
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
28186
28383
|
windowsHide: true,
|
|
28187
|
-
env:
|
|
28384
|
+
env: brokerEnvironment(options)
|
|
28188
28385
|
});
|
|
28189
28386
|
let settled = false;
|
|
28190
28387
|
const finish = (error) => {
|
|
@@ -28236,31 +28433,97 @@ async function acquireBrokerCredential(options) {
|
|
|
28236
28433
|
},
|
|
28237
28434
|
{ signal: options.signal }
|
|
28238
28435
|
);
|
|
28436
|
+
}
|
|
28437
|
+
async function forwardOnce(descriptor, environment, request3, signal) {
|
|
28438
|
+
const body = JSON.stringify({
|
|
28439
|
+
generation: environment.generation,
|
|
28440
|
+
timestamp: Date.now(),
|
|
28441
|
+
method: request3.method,
|
|
28442
|
+
path: request3.path,
|
|
28443
|
+
headers: request3.headers ?? {},
|
|
28444
|
+
...request3.body === void 0 ? {} : { body: request3.body }
|
|
28445
|
+
});
|
|
28446
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
|
|
28447
|
+
method: "POST",
|
|
28448
|
+
body,
|
|
28449
|
+
signal,
|
|
28450
|
+
headers: {
|
|
28451
|
+
"Content-Type": "application/json",
|
|
28452
|
+
"X-Prim-Proof": signature(
|
|
28453
|
+
environment.clientSecret,
|
|
28454
|
+
descriptor.nonce,
|
|
28455
|
+
body,
|
|
28456
|
+
FORWARD_REQUEST_PROOF
|
|
28457
|
+
)
|
|
28458
|
+
}
|
|
28459
|
+
});
|
|
28460
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
|
|
28461
|
+
if (typeof envelope.body !== "string" || !matches(
|
|
28462
|
+
signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
|
|
28463
|
+
envelope.proof
|
|
28464
|
+
))
|
|
28465
|
+
throw new MachineAuthError(
|
|
28466
|
+
"broker_unavailable",
|
|
28467
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
28468
|
+
);
|
|
28469
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
28470
|
+
if (data.error) {
|
|
28471
|
+
const error = machineRecord(data.error);
|
|
28472
|
+
throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
|
|
28473
|
+
}
|
|
28474
|
+
const status = data.status;
|
|
28475
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
|
|
28476
|
+
throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
|
|
28477
|
+
const headers = new Headers();
|
|
28478
|
+
for (const [name2, value] of Object.entries(machineRecord(data.headers ?? {})))
|
|
28479
|
+
if (typeof value === "string") headers.set(name2, value);
|
|
28480
|
+
const text = typeof data.body === "string" ? data.body : "";
|
|
28481
|
+
return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
|
|
28482
|
+
}
|
|
28483
|
+
async function forwardBrokerRequest(options) {
|
|
28484
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
28485
|
+
const unavailable = () => new MachineAuthError(
|
|
28486
|
+
"broker_unavailable",
|
|
28487
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
28488
|
+
);
|
|
28489
|
+
const existing = readDescriptor(path);
|
|
28490
|
+
if (existing) {
|
|
28491
|
+
try {
|
|
28492
|
+
return await forwardOnce(existing, options.environment, options.request, options.signal);
|
|
28493
|
+
} catch (error) {
|
|
28494
|
+
options.signal.throwIfAborted();
|
|
28495
|
+
if (error instanceof MachineAuthError) throw error;
|
|
28496
|
+
if (error.code !== "ECONNREFUSED") throw unavailable();
|
|
28497
|
+
}
|
|
28498
|
+
}
|
|
28499
|
+
const descriptor = await ensureBroker(options);
|
|
28239
28500
|
try {
|
|
28240
|
-
return await
|
|
28501
|
+
return await forwardOnce(descriptor, options.environment, options.request, options.signal);
|
|
28241
28502
|
} catch (error) {
|
|
28242
28503
|
options.signal.throwIfAborted();
|
|
28243
28504
|
if (error instanceof MachineAuthError) throw error;
|
|
28244
|
-
throw
|
|
28245
|
-
"broker_unavailable",
|
|
28246
|
-
"Machine credential broker is unavailable. Retry the command."
|
|
28247
|
-
);
|
|
28505
|
+
throw unavailable();
|
|
28248
28506
|
}
|
|
28249
28507
|
}
|
|
28250
28508
|
|
|
28251
28509
|
// src/lib/machine-retry.ts
|
|
28252
28510
|
import { createHash as createHash5 } from "crypto";
|
|
28253
|
-
import { lstatSync as lstatSync5, readFileSync as
|
|
28254
|
-
import { join as
|
|
28255
|
-
|
|
28511
|
+
import { lstatSync as lstatSync5, readFileSync as readFileSync9, readdirSync as readdirSync3, rmSync as rmSync6 } from "fs";
|
|
28512
|
+
import { join as join12 } from "path";
|
|
28513
|
+
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
28514
|
+
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
28515
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
28256
28516
|
signal?.throwIfAborted();
|
|
28257
28517
|
const key = createHash5("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
28258
|
-
const path =
|
|
28259
|
-
let state = {
|
|
28518
|
+
const path = join12(directory, `machine_retry_${key}.json`);
|
|
28519
|
+
let state = {
|
|
28520
|
+
failures: 0,
|
|
28521
|
+
retryAt: 0
|
|
28522
|
+
};
|
|
28260
28523
|
try {
|
|
28261
28524
|
const stat = lstatSync5(path);
|
|
28262
28525
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
28263
|
-
const data = JSON.parse(
|
|
28526
|
+
const data = JSON.parse(readFileSync9(path, "utf8"));
|
|
28264
28527
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
28265
28528
|
throw new Error("Invalid retry state");
|
|
28266
28529
|
state = data;
|
|
@@ -28271,13 +28534,20 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
28271
28534
|
if (state.retryAt > Date.now())
|
|
28272
28535
|
throw new MachineAuthError(
|
|
28273
28536
|
"token_service_unavailable",
|
|
28274
|
-
"Machine authentication is cooling down after a temporary failure. Retry later."
|
|
28537
|
+
!isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
|
|
28538
|
+
// Cloud setup keeps this wait too, so pointing at it would loop.
|
|
28539
|
+
`${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
|
|
28540
|
+
) : (
|
|
28541
|
+
// The cooldown hides the failure that started it; cloud setup
|
|
28542
|
+
// retries at once and names the cause.
|
|
28543
|
+
cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
|
|
28544
|
+
),
|
|
28275
28545
|
false,
|
|
28276
28546
|
state.retryAt
|
|
28277
28547
|
);
|
|
28278
28548
|
try {
|
|
28279
|
-
const result = await
|
|
28280
|
-
|
|
28549
|
+
const result = await request3();
|
|
28550
|
+
rmSync6(path, { force: true });
|
|
28281
28551
|
return result;
|
|
28282
28552
|
} catch (error) {
|
|
28283
28553
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -28288,40 +28558,1011 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
28288
28558
|
].includes(error.code)) {
|
|
28289
28559
|
const failures = Math.min(16, state.failures + 1);
|
|
28290
28560
|
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
28291
|
-
const retryAt = error.retryAt
|
|
28292
|
-
atomicWriteFile(
|
|
28561
|
+
const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
|
|
28562
|
+
atomicWriteFile(
|
|
28563
|
+
path,
|
|
28564
|
+
JSON.stringify({
|
|
28565
|
+
failures,
|
|
28566
|
+
retryAt,
|
|
28567
|
+
...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
|
|
28568
|
+
}),
|
|
28569
|
+
{ mode: 384 }
|
|
28570
|
+
);
|
|
28293
28571
|
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
28294
28572
|
}
|
|
28295
28573
|
throw error;
|
|
28296
28574
|
}
|
|
28297
28575
|
}
|
|
28298
28576
|
|
|
28577
|
+
// src/lib/session-identity.ts
|
|
28578
|
+
import { execFile } from "child_process";
|
|
28579
|
+
import { createHash as createHash6 } from "crypto";
|
|
28580
|
+
import { rmSync as rmSync7 } from "fs";
|
|
28581
|
+
import { join as join13 } from "path";
|
|
28582
|
+
import { promisify } from "util";
|
|
28583
|
+
|
|
28584
|
+
// src/lib/terminal-safe.ts
|
|
28585
|
+
function replaceIsolatedSurrogates(value) {
|
|
28586
|
+
let out = "";
|
|
28587
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
28588
|
+
const unit = value.charCodeAt(index);
|
|
28589
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
28590
|
+
const next = value.charCodeAt(index + 1);
|
|
28591
|
+
if (next >= 56320 && next <= 57343) {
|
|
28592
|
+
out += value[index] + value[index + 1];
|
|
28593
|
+
index += 1;
|
|
28594
|
+
} else {
|
|
28595
|
+
out += "\uFFFD";
|
|
28596
|
+
}
|
|
28597
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
28598
|
+
out += "\uFFFD";
|
|
28599
|
+
} else {
|
|
28600
|
+
out += value[index];
|
|
28601
|
+
}
|
|
28602
|
+
}
|
|
28603
|
+
return out;
|
|
28604
|
+
}
|
|
28605
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
28606
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
28607
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
28608
|
+
point === 1564 || // Arabic letter mark
|
|
28609
|
+
point === 6158 || // Mongolian vowel separator
|
|
28610
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
28611
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
28612
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
28613
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
28614
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
28615
|
+
point >= 917504 && point <= 917631;
|
|
28616
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
28617
|
+
}
|
|
28618
|
+
function terminalSafeText(value) {
|
|
28619
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
28620
|
+
}
|
|
28621
|
+
function terminalSafeLine(value) {
|
|
28622
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
28623
|
+
}
|
|
28624
|
+
|
|
28625
|
+
// src/lib/session-identity.ts
|
|
28626
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
28627
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
28628
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
28629
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
28630
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
28631
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
28632
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
28633
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
28634
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
28635
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
28636
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
28637
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
28638
|
+
token: "/api/cli/session-identity/token",
|
|
28639
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
28640
|
+
link: "/api/cli/session-identity/link"
|
|
28641
|
+
};
|
|
28642
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
28643
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
28644
|
+
var GIT_TIMEOUT_MS3 = 1e4;
|
|
28645
|
+
var POLL_BUDGET_MS = 15e3;
|
|
28646
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
28647
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
28648
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
28649
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
28650
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
28651
|
+
function sessionIdentityRequested(env = process.env) {
|
|
28652
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
28653
|
+
}
|
|
28654
|
+
function sessionIdentityMode(deps = {}) {
|
|
28655
|
+
const env = deps.env ?? process.env;
|
|
28656
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
28657
|
+
}
|
|
28658
|
+
function failure(code, cause, remedy) {
|
|
28659
|
+
return { status: "failed", code, cause, remedy };
|
|
28660
|
+
}
|
|
28661
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
28662
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
28663
|
+
var ENVIRONMENT_CREDENTIAL_REMEDY = 'ask the organization admin who set up the environment to check its credential, or to mint a replacement with `prim auth enroll --new-environment "<name>" --print-env`; then start a new cloud session';
|
|
28664
|
+
var SESSION_REVOKED = failure(
|
|
28665
|
+
"session_revoked",
|
|
28666
|
+
"Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
|
|
28667
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
28668
|
+
);
|
|
28669
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
28670
|
+
"challenge_expired",
|
|
28671
|
+
"this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
|
|
28672
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
28673
|
+
);
|
|
28674
|
+
var CHALLENGE_GONE = failure(
|
|
28675
|
+
"challenge_not_found",
|
|
28676
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
28677
|
+
NEW_SESSION_REMEDY
|
|
28678
|
+
);
|
|
28679
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
28680
|
+
function rejectionFailure(reason, repository) {
|
|
28681
|
+
switch (reason) {
|
|
28682
|
+
case "identity_mismatch":
|
|
28683
|
+
return failure(
|
|
28684
|
+
"identity_mismatch",
|
|
28685
|
+
"the session branch was created by a GitHub account linked to a different Primitive member than the one signed in to Claude, so Primitive attributes this session to no one",
|
|
28686
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
28687
|
+
);
|
|
28688
|
+
case "push_after_expiry":
|
|
28689
|
+
return failure(
|
|
28690
|
+
"push_after_expiry",
|
|
28691
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
28692
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
28693
|
+
);
|
|
28694
|
+
case "repository_mismatch":
|
|
28695
|
+
return failure(
|
|
28696
|
+
"repository_mismatch",
|
|
28697
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
28698
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
28699
|
+
);
|
|
28700
|
+
case "conflicting_push":
|
|
28701
|
+
return failure(
|
|
28702
|
+
"conflicting_push",
|
|
28703
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
28704
|
+
NEW_SESSION_REMEDY
|
|
28705
|
+
);
|
|
28706
|
+
case "unsupported_sender":
|
|
28707
|
+
return failure(
|
|
28708
|
+
"unsupported_sender",
|
|
28709
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
28710
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
28711
|
+
);
|
|
28712
|
+
default:
|
|
28713
|
+
return failure(
|
|
28714
|
+
"challenge_rejected",
|
|
28715
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
28716
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
28717
|
+
);
|
|
28718
|
+
}
|
|
28719
|
+
}
|
|
28720
|
+
function sessionIdentityMessage(outcome) {
|
|
28721
|
+
if (outcome.status === "link_required")
|
|
28722
|
+
return `GitHub account @${outcome.githubLogin} started this Claude Code cloud session but is not linked to a Primitive account yet. To link it once, run \`prim auth link\` and sign in at the URL it prints with the code it shows; later sessions then identify you automatically.`;
|
|
28723
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
28724
|
+
}
|
|
28725
|
+
function hash(value) {
|
|
28726
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
28727
|
+
}
|
|
28728
|
+
function sessionContext(deps) {
|
|
28729
|
+
const env = deps.env ?? process.env;
|
|
28730
|
+
const environment = environmentCredentials(deps);
|
|
28731
|
+
if (!environment)
|
|
28732
|
+
return failure(
|
|
28733
|
+
"environment_credential_missing",
|
|
28734
|
+
"the cloud environment has no environment credential",
|
|
28735
|
+
'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
|
|
28736
|
+
);
|
|
28737
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
28738
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
28739
|
+
return failure(
|
|
28740
|
+
"session_id_missing",
|
|
28741
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
28742
|
+
NEW_SESSION_REMEDY
|
|
28743
|
+
);
|
|
28744
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
28745
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
28746
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
28747
|
+
return {
|
|
28748
|
+
directory,
|
|
28749
|
+
apiUrl,
|
|
28750
|
+
clientId: environment.clientId,
|
|
28751
|
+
generation: environment.generation,
|
|
28752
|
+
sessionId,
|
|
28753
|
+
tokenPath: join13(directory, `session_identity_${key}.json`),
|
|
28754
|
+
statePath: join13(directory, `session_identity_${key}.state.json`),
|
|
28755
|
+
lockPath: join13(directory, "session-identity.lock")
|
|
28756
|
+
};
|
|
28757
|
+
}
|
|
28758
|
+
function readRecord(path) {
|
|
28759
|
+
try {
|
|
28760
|
+
const value = readMachineMetadata(path);
|
|
28761
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
28762
|
+
} catch {
|
|
28763
|
+
return void 0;
|
|
28764
|
+
}
|
|
28765
|
+
}
|
|
28766
|
+
function finiteNumber(value) {
|
|
28767
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
28768
|
+
}
|
|
28769
|
+
function readToken(context) {
|
|
28770
|
+
const data = readRecord(context.tokenPath);
|
|
28771
|
+
if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
|
|
28772
|
+
return void 0;
|
|
28773
|
+
const identity = data.identity;
|
|
28774
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
28775
|
+
return void 0;
|
|
28776
|
+
return data;
|
|
28777
|
+
}
|
|
28778
|
+
function readState(context) {
|
|
28779
|
+
const data = readRecord(context.statePath);
|
|
28780
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
28781
|
+
return void 0;
|
|
28782
|
+
return data;
|
|
28783
|
+
}
|
|
28784
|
+
function writeToken(context, record) {
|
|
28785
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
28786
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
28787
|
+
rmSync7(context.statePath, { force: true });
|
|
28788
|
+
}
|
|
28789
|
+
function writeState(context, state) {
|
|
28790
|
+
try {
|
|
28791
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
28792
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
28793
|
+
} catch {
|
|
28794
|
+
}
|
|
28795
|
+
}
|
|
28796
|
+
function tokenValid(record, now = Date.now()) {
|
|
28797
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
28798
|
+
}
|
|
28799
|
+
function tokenFresh(record, now = Date.now()) {
|
|
28800
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
28801
|
+
}
|
|
28802
|
+
function toCredential(record) {
|
|
28803
|
+
return {
|
|
28804
|
+
issuer: record.issuer,
|
|
28805
|
+
audience: record.audience,
|
|
28806
|
+
...record.identity,
|
|
28807
|
+
accessToken: record.accessToken,
|
|
28808
|
+
expiresAt: record.expiresAt,
|
|
28809
|
+
apiUrl: record.apiUrl,
|
|
28810
|
+
generation: record.generation,
|
|
28811
|
+
storage: "environment",
|
|
28812
|
+
session: {
|
|
28813
|
+
userId: record.userId,
|
|
28814
|
+
displayName: record.displayName,
|
|
28815
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
28816
|
+
refreshAfter: record.refreshAfter
|
|
28817
|
+
}
|
|
28818
|
+
};
|
|
28819
|
+
}
|
|
28820
|
+
function identified(record, reused) {
|
|
28821
|
+
return {
|
|
28822
|
+
status: "ok",
|
|
28823
|
+
credential: toCredential(record),
|
|
28824
|
+
displayName: record.displayName,
|
|
28825
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
28826
|
+
reused
|
|
28827
|
+
};
|
|
28828
|
+
}
|
|
28829
|
+
function cachedSessionCredential(deps = {}) {
|
|
28830
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
28831
|
+
let context;
|
|
28832
|
+
try {
|
|
28833
|
+
context = sessionContext(deps);
|
|
28834
|
+
} catch {
|
|
28835
|
+
return void 0;
|
|
28836
|
+
}
|
|
28837
|
+
if ("status" in context) return void 0;
|
|
28838
|
+
const record = readToken(context);
|
|
28839
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
28840
|
+
}
|
|
28841
|
+
function outcomeFromState(state) {
|
|
28842
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
28843
|
+
return {
|
|
28844
|
+
status: "link_required",
|
|
28845
|
+
githubLogin: state.githubLogin,
|
|
28846
|
+
challengeId: state.challengeId,
|
|
28847
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
28848
|
+
};
|
|
28849
|
+
return failure(
|
|
28850
|
+
state.code,
|
|
28851
|
+
state.cause ?? "the last identity check failed",
|
|
28852
|
+
state.remedy ?? RETRY_REMEDY
|
|
28853
|
+
);
|
|
28854
|
+
}
|
|
28855
|
+
function parseInstant(value) {
|
|
28856
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
28857
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
28858
|
+
const parsed = Date.parse(value);
|
|
28859
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
28860
|
+
}
|
|
28861
|
+
return void 0;
|
|
28862
|
+
}
|
|
28863
|
+
async function sendJson(url, init, fetchImpl) {
|
|
28864
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
28865
|
+
let value;
|
|
28866
|
+
try {
|
|
28867
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
28868
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
28869
|
+
} catch {
|
|
28870
|
+
value = void 0;
|
|
28871
|
+
}
|
|
28872
|
+
return { status: response.status, value };
|
|
28873
|
+
}
|
|
28874
|
+
function environmentOnly(deps) {
|
|
28875
|
+
return { ...deps, environmentOnly: true };
|
|
28876
|
+
}
|
|
28877
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
28878
|
+
const send = async (credential2) => {
|
|
28879
|
+
const headers = { "Content-Type": "application/json" };
|
|
28880
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
28881
|
+
if (credential2.tokenInjection) {
|
|
28882
|
+
const response = await forwardMachineRequest(
|
|
28883
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
28884
|
+
signal,
|
|
28885
|
+
environmentOnly(deps)
|
|
28886
|
+
);
|
|
28887
|
+
const parsed = await response.json().catch(() => void 0);
|
|
28888
|
+
return {
|
|
28889
|
+
status: response.status,
|
|
28890
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
28891
|
+
};
|
|
28892
|
+
}
|
|
28893
|
+
return sendJson(
|
|
28894
|
+
`${credential2.apiUrl}${path}`,
|
|
28895
|
+
{
|
|
28896
|
+
method,
|
|
28897
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
28898
|
+
...text === void 0 ? {} : { body: text },
|
|
28899
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS3)
|
|
28900
|
+
},
|
|
28901
|
+
deps.fetch ?? fetch
|
|
28902
|
+
);
|
|
28903
|
+
};
|
|
28904
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
28905
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
28906
|
+
let answer = await send(credential);
|
|
28907
|
+
if (answer.status === 401) {
|
|
28908
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
28909
|
+
if (!credential)
|
|
28910
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
28911
|
+
answer = await send(credential);
|
|
28912
|
+
}
|
|
28913
|
+
return answer;
|
|
28914
|
+
}
|
|
28915
|
+
function environmentFailure(error, apiUrl) {
|
|
28916
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
28917
|
+
return failure(
|
|
28918
|
+
"environment_credential_rejected",
|
|
28919
|
+
"Primitive rejected the cloud environment's credential",
|
|
28920
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
28921
|
+
);
|
|
28922
|
+
const host = (() => {
|
|
28923
|
+
try {
|
|
28924
|
+
return new URL(apiUrl).hostname;
|
|
28925
|
+
} catch {
|
|
28926
|
+
return "Primitive";
|
|
28927
|
+
}
|
|
28928
|
+
})();
|
|
28929
|
+
return failure(
|
|
28930
|
+
"identity_unavailable",
|
|
28931
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
28932
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
28933
|
+
);
|
|
28934
|
+
}
|
|
28935
|
+
function answerError(answer) {
|
|
28936
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
28937
|
+
}
|
|
28938
|
+
async function git(root, args, signal) {
|
|
28939
|
+
try {
|
|
28940
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
28941
|
+
cwd: root,
|
|
28942
|
+
encoding: "utf8",
|
|
28943
|
+
timeout: GIT_TIMEOUT_MS3,
|
|
28944
|
+
signal,
|
|
28945
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
28946
|
+
maxBuffer: 1024 * 1024
|
|
28947
|
+
});
|
|
28948
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
28949
|
+
} catch (error) {
|
|
28950
|
+
const failed = error;
|
|
28951
|
+
return {
|
|
28952
|
+
ok: false,
|
|
28953
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
28954
|
+
stdout: failed.stdout ?? "",
|
|
28955
|
+
stderr: failed.stderr ?? "",
|
|
28956
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
28957
|
+
};
|
|
28958
|
+
}
|
|
28959
|
+
}
|
|
28960
|
+
function gitDetail(stderr) {
|
|
28961
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
28962
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
28963
|
+
}
|
|
28964
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
28965
|
+
await new Promise((resolve7, reject) => {
|
|
28966
|
+
const timer = setTimeout(resolve7, milliseconds);
|
|
28967
|
+
signal?.addEventListener(
|
|
28968
|
+
"abort",
|
|
28969
|
+
() => {
|
|
28970
|
+
clearTimeout(timer);
|
|
28971
|
+
reject(signal.reason);
|
|
28972
|
+
},
|
|
28973
|
+
{ once: true }
|
|
28974
|
+
);
|
|
28975
|
+
});
|
|
28976
|
+
}
|
|
28977
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
28978
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
28979
|
+
const deadline2 = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
28980
|
+
let delay2 = POLL_FIRST_DELAY_MS;
|
|
28981
|
+
let unreachable;
|
|
28982
|
+
for (; ; ) {
|
|
28983
|
+
const remaining = deadline2 - Date.now();
|
|
28984
|
+
if (remaining <= 0) break;
|
|
28985
|
+
await sleep(Math.min(delay2, remaining), signal);
|
|
28986
|
+
delay2 = Math.min(POLL_MAX_DELAY_MS, Math.round(delay2 * 1.5));
|
|
28987
|
+
let answer;
|
|
28988
|
+
try {
|
|
28989
|
+
answer = await environmentRequest(
|
|
28990
|
+
"GET",
|
|
28991
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
28992
|
+
void 0,
|
|
28993
|
+
deps,
|
|
28994
|
+
signal
|
|
28995
|
+
);
|
|
28996
|
+
} catch (error) {
|
|
28997
|
+
signal?.throwIfAborted();
|
|
28998
|
+
unreachable = error;
|
|
28999
|
+
continue;
|
|
29000
|
+
}
|
|
29001
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
29002
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29003
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
29004
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
29005
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
29006
|
+
continue;
|
|
29007
|
+
}
|
|
29008
|
+
unreachable = void 0;
|
|
29009
|
+
const status = answer.value;
|
|
29010
|
+
if (status?.status === "verified")
|
|
29011
|
+
return {
|
|
29012
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
29013
|
+
};
|
|
29014
|
+
if (status?.status === "expired")
|
|
29015
|
+
return failure(
|
|
29016
|
+
"challenge_expired",
|
|
29017
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
29018
|
+
NEW_SESSION_REMEDY
|
|
29019
|
+
);
|
|
29020
|
+
if (status?.status === "rejected")
|
|
29021
|
+
return rejectionFailure(status.reason, repository);
|
|
29022
|
+
}
|
|
29023
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
29024
|
+
return failure(
|
|
29025
|
+
"webhook_timeout",
|
|
29026
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
29027
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
29028
|
+
);
|
|
29029
|
+
}
|
|
29030
|
+
function parseTokenAnswer(value) {
|
|
29031
|
+
if (!value) return void 0;
|
|
29032
|
+
const user = value.user;
|
|
29033
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
29034
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
29035
|
+
if (!machineString(value.accessToken, 8192) || !value.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !expiresAt || !refreshAfter || !user || !machineString(user.id, 256) || !machineString(user.displayName, 256) || !machineString(value.organizationId, 256))
|
|
29036
|
+
return void 0;
|
|
29037
|
+
return {
|
|
29038
|
+
accessToken: value.accessToken,
|
|
29039
|
+
expiresAt,
|
|
29040
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
29041
|
+
userId: user.id,
|
|
29042
|
+
displayName: user.displayName,
|
|
29043
|
+
organizationId: value.organizationId
|
|
29044
|
+
};
|
|
29045
|
+
}
|
|
29046
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
29047
|
+
"server_contract",
|
|
29048
|
+
"Primitive's answer did not identify the linked member",
|
|
29049
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
29050
|
+
);
|
|
29051
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
29052
|
+
let identity;
|
|
29053
|
+
let environment;
|
|
29054
|
+
try {
|
|
29055
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
29056
|
+
identity = await verifyMachineIdentity(
|
|
29057
|
+
context.apiUrl,
|
|
29058
|
+
answer.accessToken,
|
|
29059
|
+
context.clientId,
|
|
29060
|
+
signal,
|
|
29061
|
+
deps.fetch
|
|
29062
|
+
);
|
|
29063
|
+
} catch (error) {
|
|
29064
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
29065
|
+
return SERVER_CONTRACT_FAILURE;
|
|
29066
|
+
return environmentFailure(error, context.apiUrl);
|
|
29067
|
+
}
|
|
29068
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
29069
|
+
return SERVER_CONTRACT_FAILURE;
|
|
29070
|
+
return {
|
|
29071
|
+
version: 1,
|
|
29072
|
+
apiUrl: context.apiUrl,
|
|
29073
|
+
clientId: context.clientId,
|
|
29074
|
+
generation: context.generation,
|
|
29075
|
+
sessionId: context.sessionId,
|
|
29076
|
+
issuer: environment.issuer,
|
|
29077
|
+
audience: environment.audience,
|
|
29078
|
+
accessToken: answer.accessToken,
|
|
29079
|
+
expiresAt: answer.expiresAt,
|
|
29080
|
+
refreshAfter: answer.refreshAfter,
|
|
29081
|
+
userId: answer.userId,
|
|
29082
|
+
displayName: answer.displayName,
|
|
29083
|
+
organizationId: answer.organizationId,
|
|
29084
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
29085
|
+
identity,
|
|
29086
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
29087
|
+
};
|
|
29088
|
+
}
|
|
29089
|
+
async function refreshToken(context, record, deps, signal) {
|
|
29090
|
+
let answer;
|
|
29091
|
+
try {
|
|
29092
|
+
answer = await environmentRequest(
|
|
29093
|
+
"POST",
|
|
29094
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
29095
|
+
{ accessToken: record.accessToken },
|
|
29096
|
+
deps,
|
|
29097
|
+
signal
|
|
29098
|
+
);
|
|
29099
|
+
} catch (error) {
|
|
29100
|
+
signal?.throwIfAborted();
|
|
29101
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
29102
|
+
}
|
|
29103
|
+
const code = answerError(answer);
|
|
29104
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
29105
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
29106
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29107
|
+
return {
|
|
29108
|
+
status: "refused",
|
|
29109
|
+
failure: environmentFailure(
|
|
29110
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
29111
|
+
context.apiUrl
|
|
29112
|
+
)
|
|
29113
|
+
};
|
|
29114
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
29115
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
29116
|
+
return { status: "unavailable" };
|
|
29117
|
+
return {
|
|
29118
|
+
status: "ok",
|
|
29119
|
+
record: {
|
|
29120
|
+
...record,
|
|
29121
|
+
accessToken: token.accessToken,
|
|
29122
|
+
expiresAt: token.expiresAt,
|
|
29123
|
+
refreshAfter: token.refreshAfter,
|
|
29124
|
+
displayName: token.displayName
|
|
29125
|
+
}
|
|
29126
|
+
};
|
|
29127
|
+
}
|
|
29128
|
+
function exchangeRefusal(answer, repository) {
|
|
29129
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
29130
|
+
if (answer.status !== 409) return void 0;
|
|
29131
|
+
switch (answerError(answer)) {
|
|
29132
|
+
case "identity_mismatch":
|
|
29133
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
29134
|
+
case "challenge_rejected":
|
|
29135
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
29136
|
+
case "challenge_expired":
|
|
29137
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
29138
|
+
case "challenge_already_exchanged":
|
|
29139
|
+
return failure(
|
|
29140
|
+
"challenge_already_exchanged",
|
|
29141
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
29142
|
+
NEW_SESSION_REMEDY
|
|
29143
|
+
);
|
|
29144
|
+
case "challenge_pending":
|
|
29145
|
+
return failure(
|
|
29146
|
+
"webhook_timeout",
|
|
29147
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
29148
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
29149
|
+
);
|
|
29150
|
+
default:
|
|
29151
|
+
return void 0;
|
|
29152
|
+
}
|
|
29153
|
+
}
|
|
29154
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
29155
|
+
let answer;
|
|
29156
|
+
try {
|
|
29157
|
+
answer = await environmentRequest(
|
|
29158
|
+
"POST",
|
|
29159
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
29160
|
+
{ challengeId: challenge.challengeId },
|
|
29161
|
+
deps,
|
|
29162
|
+
signal
|
|
29163
|
+
);
|
|
29164
|
+
} catch (error) {
|
|
29165
|
+
signal?.throwIfAborted();
|
|
29166
|
+
return environmentFailure(error, context.apiUrl);
|
|
29167
|
+
}
|
|
29168
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
29169
|
+
const login = answer.value?.githubLogin;
|
|
29170
|
+
return {
|
|
29171
|
+
status: "link_required",
|
|
29172
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
29173
|
+
challengeId: challenge.challengeId,
|
|
29174
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
29175
|
+
};
|
|
29176
|
+
}
|
|
29177
|
+
const refused = exchangeRefusal(
|
|
29178
|
+
answer,
|
|
29179
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
29180
|
+
);
|
|
29181
|
+
if (refused) return refused;
|
|
29182
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
29183
|
+
if (!token) {
|
|
29184
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29185
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
29186
|
+
return answer.status >= 500 ? environmentFailure(
|
|
29187
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
29188
|
+
context.apiUrl
|
|
29189
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
29190
|
+
}
|
|
29191
|
+
return recordFor(
|
|
29192
|
+
context,
|
|
29193
|
+
token,
|
|
29194
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
29195
|
+
deps,
|
|
29196
|
+
signal
|
|
29197
|
+
);
|
|
29198
|
+
}
|
|
29199
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
29200
|
+
const env = deps.env ?? process.env;
|
|
29201
|
+
const repository = githubRepositoryFullName(root);
|
|
29202
|
+
if (!repository)
|
|
29203
|
+
return failure(
|
|
29204
|
+
"repository_unidentified",
|
|
29205
|
+
"this checkout does not name its GitHub repository",
|
|
29206
|
+
"run it in the repository the session cloned; for a checkout with no GitHub origin, commit its repository declaration with `prim claude install --scope project` from a clone whose origin is on GitHub"
|
|
29207
|
+
);
|
|
29208
|
+
const branch = currentBranch(root);
|
|
29209
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
29210
|
+
return failure(
|
|
29211
|
+
"not_session_branch",
|
|
29212
|
+
`this checkout is on ${branch ? `branch ${terminalSafeLine(branch).slice(0, 120)}` : "a detached HEAD"}, not the session's own claude/\u2026 branch, so prim cannot prove who started the session and pushed nothing`,
|
|
29213
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
29214
|
+
);
|
|
29215
|
+
attempt.branch = branch;
|
|
29216
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
29217
|
+
if (!baseSha) {
|
|
29218
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
29219
|
+
baseSha = head.stdout.trim();
|
|
29220
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
29221
|
+
return failure(
|
|
29222
|
+
"no_commit",
|
|
29223
|
+
"this checkout has no commit to create the session branch at",
|
|
29224
|
+
NEW_SESSION_REMEDY
|
|
29225
|
+
);
|
|
29226
|
+
}
|
|
29227
|
+
const published = await git(
|
|
29228
|
+
root,
|
|
29229
|
+
[
|
|
29230
|
+
"for-each-ref",
|
|
29231
|
+
"--count=1",
|
|
29232
|
+
"--format=%(refname)",
|
|
29233
|
+
"--contains",
|
|
29234
|
+
baseSha,
|
|
29235
|
+
"refs/remotes/origin/"
|
|
29236
|
+
],
|
|
29237
|
+
signal
|
|
29238
|
+
);
|
|
29239
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
29240
|
+
return failure(
|
|
29241
|
+
"unpublished_commits",
|
|
29242
|
+
`this checkout's commit ${baseSha.slice(0, 12)} is not on GitHub yet, and creating the session branch at it would publish it, so prim pushed nothing`,
|
|
29243
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
29244
|
+
);
|
|
29245
|
+
attempt.baseSha = baseSha;
|
|
29246
|
+
const remote = await git(
|
|
29247
|
+
root,
|
|
29248
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
29249
|
+
signal
|
|
29250
|
+
);
|
|
29251
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
29252
|
+
if (remote.ok && recorded) {
|
|
29253
|
+
Object.assign(attempt, recorded);
|
|
29254
|
+
return { ...recorded, repository };
|
|
29255
|
+
}
|
|
29256
|
+
if (remote.ok)
|
|
29257
|
+
return failure(
|
|
29258
|
+
"branch_exists",
|
|
29259
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
29260
|
+
NEW_SESSION_REMEDY
|
|
29261
|
+
);
|
|
29262
|
+
if (remote.code !== 2)
|
|
29263
|
+
return failure(
|
|
29264
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
29265
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
29266
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
29267
|
+
);
|
|
29268
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
29269
|
+
Object.assign(attempt, recorded);
|
|
29270
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
29271
|
+
}
|
|
29272
|
+
let answer;
|
|
29273
|
+
try {
|
|
29274
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
29275
|
+
answer = await environmentRequest(
|
|
29276
|
+
"POST",
|
|
29277
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
29278
|
+
{
|
|
29279
|
+
repositoryFullName: repository,
|
|
29280
|
+
claudeSessionId: context.sessionId,
|
|
29281
|
+
branch,
|
|
29282
|
+
baseSha,
|
|
29283
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
29284
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
29285
|
+
},
|
|
29286
|
+
deps,
|
|
29287
|
+
signal
|
|
29288
|
+
);
|
|
29289
|
+
} catch (error) {
|
|
29290
|
+
signal?.throwIfAborted();
|
|
29291
|
+
return environmentFailure(error, context.apiUrl);
|
|
29292
|
+
}
|
|
29293
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
29294
|
+
return failure(
|
|
29295
|
+
"repository_not_connected",
|
|
29296
|
+
`${repository} is not connected to Primitive`,
|
|
29297
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
29298
|
+
);
|
|
29299
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29300
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
29301
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
29302
|
+
return failure(
|
|
29303
|
+
"challenge_open",
|
|
29304
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
29305
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
29306
|
+
);
|
|
29307
|
+
if (answer.status === 429)
|
|
29308
|
+
return failure(
|
|
29309
|
+
"too_many_challenges",
|
|
29310
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
29311
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
29312
|
+
);
|
|
29313
|
+
const challengeId = answer.value?.challengeId;
|
|
29314
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
29315
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
29316
|
+
return answer.status >= 500 ? environmentFailure(
|
|
29317
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
29318
|
+
context.apiUrl
|
|
29319
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
29320
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
29321
|
+
attempt.challengeId = challengeId;
|
|
29322
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
29323
|
+
return pushSessionBranch(
|
|
29324
|
+
root,
|
|
29325
|
+
repository,
|
|
29326
|
+
branch,
|
|
29327
|
+
baseSha,
|
|
29328
|
+
{ challengeId, challengeExpiresAt },
|
|
29329
|
+
signal
|
|
29330
|
+
);
|
|
29331
|
+
}
|
|
29332
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
29333
|
+
const push = await git(
|
|
29334
|
+
root,
|
|
29335
|
+
[
|
|
29336
|
+
"-c",
|
|
29337
|
+
"core.hooksPath=/dev/null",
|
|
29338
|
+
"-c",
|
|
29339
|
+
"push.followTags=false",
|
|
29340
|
+
"-c",
|
|
29341
|
+
"push.recurseSubmodules=no",
|
|
29342
|
+
"-c",
|
|
29343
|
+
"push.gpgSign=false",
|
|
29344
|
+
"-c",
|
|
29345
|
+
"push.pushOption=",
|
|
29346
|
+
"push",
|
|
29347
|
+
"--no-verify",
|
|
29348
|
+
"--no-follow-tags",
|
|
29349
|
+
"--no-recurse-submodules",
|
|
29350
|
+
"--no-signed",
|
|
29351
|
+
"--quiet",
|
|
29352
|
+
"origin",
|
|
29353
|
+
`${baseSha}:refs/heads/${branch}`
|
|
29354
|
+
],
|
|
29355
|
+
signal
|
|
29356
|
+
);
|
|
29357
|
+
if (!push.ok)
|
|
29358
|
+
return push.timedOut ? failure(
|
|
29359
|
+
"push_timeout",
|
|
29360
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS3 / 1e3} s`,
|
|
29361
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
29362
|
+
) : failure(
|
|
29363
|
+
"push_refused",
|
|
29364
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
29365
|
+
`check that the GitHub account that started this session can push to ${repository} and that the cloud environment lets the session push, then ${NEW_SESSION_REMEDY}`
|
|
29366
|
+
);
|
|
29367
|
+
return { ...challenge, repository };
|
|
29368
|
+
}
|
|
29369
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
29370
|
+
let context;
|
|
29371
|
+
try {
|
|
29372
|
+
context = sessionContext(deps);
|
|
29373
|
+
} catch (error) {
|
|
29374
|
+
return failure(
|
|
29375
|
+
"environment_credential_invalid",
|
|
29376
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
29377
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
29378
|
+
);
|
|
29379
|
+
}
|
|
29380
|
+
if ("status" in context) return context;
|
|
29381
|
+
const ctx = context;
|
|
29382
|
+
const startedAt = Date.now();
|
|
29383
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
29384
|
+
return withFileLock(
|
|
29385
|
+
ctx.lockPath,
|
|
29386
|
+
async () => {
|
|
29387
|
+
const record = readToken(ctx);
|
|
29388
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
29389
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
29390
|
+
if (record) {
|
|
29391
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
29392
|
+
if (refreshed.status === "ok") {
|
|
29393
|
+
writeToken(ctx, refreshed.record);
|
|
29394
|
+
return identified(refreshed.record, true);
|
|
29395
|
+
}
|
|
29396
|
+
if (refreshed.status === "refused") {
|
|
29397
|
+
rmSync7(ctx.tokenPath, { force: true });
|
|
29398
|
+
writeState(ctx, {
|
|
29399
|
+
sessionId: ctx.sessionId,
|
|
29400
|
+
status: "failed",
|
|
29401
|
+
code: refreshed.failure.code,
|
|
29402
|
+
cause: refreshed.failure.cause,
|
|
29403
|
+
remedy: refreshed.failure.remedy,
|
|
29404
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
29405
|
+
at: Date.now()
|
|
29406
|
+
});
|
|
29407
|
+
return refreshed.failure;
|
|
29408
|
+
}
|
|
29409
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
29410
|
+
}
|
|
29411
|
+
const state = readState(ctx);
|
|
29412
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
29413
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
29414
|
+
if (!options.explicit) {
|
|
29415
|
+
if (!root || !(record || state))
|
|
29416
|
+
return failure(
|
|
29417
|
+
"not_identified",
|
|
29418
|
+
"this session has not identified who started it yet",
|
|
29419
|
+
RETRY_REMEDY
|
|
29420
|
+
);
|
|
29421
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
29422
|
+
} else if (state && state.at >= startedAt) {
|
|
29423
|
+
return outcomeFromState(state);
|
|
29424
|
+
}
|
|
29425
|
+
if (!root)
|
|
29426
|
+
return failure(
|
|
29427
|
+
"repository_missing",
|
|
29428
|
+
"this is not a git repository",
|
|
29429
|
+
"run it in the repository the session cloned"
|
|
29430
|
+
);
|
|
29431
|
+
const attempt = { root };
|
|
29432
|
+
const remember = (outcome) => {
|
|
29433
|
+
writeState(ctx, {
|
|
29434
|
+
sessionId: ctx.sessionId,
|
|
29435
|
+
status: outcome.status,
|
|
29436
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
29437
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
29438
|
+
githubLogin: outcome.githubLogin
|
|
29439
|
+
},
|
|
29440
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
29441
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
29442
|
+
repositoryRoot: root,
|
|
29443
|
+
branch: attempt.branch ?? state?.branch,
|
|
29444
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
29445
|
+
at: Date.now()
|
|
29446
|
+
});
|
|
29447
|
+
return outcome;
|
|
29448
|
+
};
|
|
29449
|
+
let challenge;
|
|
29450
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
29451
|
+
attempt.challengeId = state.challengeId;
|
|
29452
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
29453
|
+
attempt.branch = state.branch;
|
|
29454
|
+
attempt.baseSha = state.baseSha;
|
|
29455
|
+
challenge = {
|
|
29456
|
+
challengeId: state.challengeId,
|
|
29457
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
29458
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
29459
|
+
};
|
|
29460
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
29461
|
+
attempt.challengeId = state.challengeId;
|
|
29462
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
29463
|
+
const exchanged2 = await exchangeChallenge(
|
|
29464
|
+
ctx,
|
|
29465
|
+
{
|
|
29466
|
+
challengeId: state.challengeId,
|
|
29467
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
29468
|
+
githubLogin: state.githubLogin
|
|
29469
|
+
},
|
|
29470
|
+
root,
|
|
29471
|
+
deps,
|
|
29472
|
+
options.signal
|
|
29473
|
+
);
|
|
29474
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
29475
|
+
writeToken(ctx, exchanged2);
|
|
29476
|
+
return identified(exchanged2, false);
|
|
29477
|
+
} else if (!options.explicit) {
|
|
29478
|
+
return state ? outcomeFromState(state) : failure(
|
|
29479
|
+
"not_identified",
|
|
29480
|
+
"this session has not identified who started it yet",
|
|
29481
|
+
RETRY_REMEDY
|
|
29482
|
+
);
|
|
29483
|
+
} else {
|
|
29484
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
29485
|
+
if ("status" in pushed) return remember(pushed);
|
|
29486
|
+
challenge = pushed;
|
|
29487
|
+
}
|
|
29488
|
+
const verified = await pollChallenge(
|
|
29489
|
+
ctx.apiUrl,
|
|
29490
|
+
challenge.challengeId,
|
|
29491
|
+
challenge.repository,
|
|
29492
|
+
// A hook process waits only briefly for a late notice.
|
|
29493
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
29494
|
+
options.signal
|
|
29495
|
+
);
|
|
29496
|
+
if ("status" in verified) return remember(verified);
|
|
29497
|
+
const exchanged = await exchangeChallenge(
|
|
29498
|
+
ctx,
|
|
29499
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
29500
|
+
root,
|
|
29501
|
+
deps,
|
|
29502
|
+
options.signal
|
|
29503
|
+
);
|
|
29504
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
29505
|
+
writeToken(ctx, exchanged);
|
|
29506
|
+
return identified(exchanged, false);
|
|
29507
|
+
},
|
|
29508
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
29509
|
+
);
|
|
29510
|
+
}
|
|
29511
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
29512
|
+
const cached2 = cachedSessionCredential(deps);
|
|
29513
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
29514
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
29515
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
29516
|
+
let outcome;
|
|
29517
|
+
try {
|
|
29518
|
+
outcome = await ensureSessionIdentity(
|
|
29519
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
29520
|
+
deps
|
|
29521
|
+
);
|
|
29522
|
+
} catch (error) {
|
|
29523
|
+
options.signal?.throwIfAborted();
|
|
29524
|
+
if (error instanceof MachineAuthError) throw error;
|
|
29525
|
+
throw new MachineAuthError(
|
|
29526
|
+
"identity_unavailable",
|
|
29527
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
29528
|
+
);
|
|
29529
|
+
}
|
|
29530
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
29531
|
+
throw new MachineAuthError(
|
|
29532
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
29533
|
+
sessionIdentityMessage(outcome)
|
|
29534
|
+
);
|
|
29535
|
+
}
|
|
29536
|
+
|
|
28299
29537
|
// src/lib/machine-credentials.ts
|
|
29538
|
+
function sessionScoped(deps) {
|
|
29539
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
29540
|
+
}
|
|
28300
29541
|
var require3 = createRequire2(import.meta.url);
|
|
28301
29542
|
var SERVICE = "ai.primitive.prim.machine";
|
|
28302
|
-
var
|
|
29543
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
28303
29544
|
var PROFILE_FILE = "machine_profile.json";
|
|
28304
|
-
var
|
|
29545
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
28305
29546
|
var cached;
|
|
28306
29547
|
function configurationDirectory(deps) {
|
|
28307
29548
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
28308
29549
|
}
|
|
28309
29550
|
function apiUrlFor(deps) {
|
|
28310
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
29551
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
28311
29552
|
}
|
|
28312
|
-
function
|
|
28313
|
-
return
|
|
29553
|
+
function hash2(value) {
|
|
29554
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
28314
29555
|
}
|
|
28315
29556
|
function recordPath(directory, generation) {
|
|
28316
|
-
return
|
|
29557
|
+
return join14(directory, `machine_${generation}.json`);
|
|
28317
29558
|
}
|
|
28318
29559
|
function storageKey(directory, generation) {
|
|
28319
|
-
return `${
|
|
29560
|
+
return `${hash2(directory)}:${generation}`;
|
|
28320
29561
|
}
|
|
28321
29562
|
function environmentContextPath(deps, clientId) {
|
|
28322
|
-
return
|
|
29563
|
+
return join14(
|
|
28323
29564
|
configurationDirectory(deps),
|
|
28324
|
-
`machine_context_${
|
|
29565
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
28325
29566
|
);
|
|
28326
29567
|
}
|
|
28327
29568
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -28382,8 +29623,8 @@ function readEnvironmentContext(environment, deps) {
|
|
|
28382
29623
|
function keyringEntry(key) {
|
|
28383
29624
|
let directory = dirname7(fileURLToPath4(import.meta.url));
|
|
28384
29625
|
for (let depth = 0; depth < 5; depth++) {
|
|
28385
|
-
const loader =
|
|
28386
|
-
if (
|
|
29626
|
+
const loader = join14(directory, "native", "keyring.cjs");
|
|
29627
|
+
if (existsSync10(loader)) {
|
|
28387
29628
|
const module2 = require3(loader);
|
|
28388
29629
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
28389
29630
|
}
|
|
@@ -28411,7 +29652,7 @@ function protectPath(path, directory) {
|
|
|
28411
29652
|
);
|
|
28412
29653
|
}
|
|
28413
29654
|
function ensureDirectory(directory) {
|
|
28414
|
-
|
|
29655
|
+
mkdirSync5(directory, { recursive: true, mode: 448 });
|
|
28415
29656
|
if (lstatSync6(directory).isSymbolicLink())
|
|
28416
29657
|
throw new MachineAuthError(
|
|
28417
29658
|
"unsafe_storage",
|
|
@@ -28424,6 +29665,9 @@ function writePrivate(path, value) {
|
|
|
28424
29665
|
`, { mode: 384 });
|
|
28425
29666
|
protectPath(path, false);
|
|
28426
29667
|
}
|
|
29668
|
+
function readMachineMetadata(path) {
|
|
29669
|
+
return readPrivate(path);
|
|
29670
|
+
}
|
|
28427
29671
|
function readPrivate(path) {
|
|
28428
29672
|
let raw;
|
|
28429
29673
|
try {
|
|
@@ -28434,7 +29678,7 @@ function readPrivate(path) {
|
|
|
28434
29678
|
"Machine credential files must be owner-only regular files."
|
|
28435
29679
|
);
|
|
28436
29680
|
}
|
|
28437
|
-
raw =
|
|
29681
|
+
raw = readFileSync10(path, "utf8");
|
|
28438
29682
|
} catch (error) {
|
|
28439
29683
|
if (error.code === "ENOENT") return void 0;
|
|
28440
29684
|
throw error;
|
|
@@ -28479,13 +29723,101 @@ function parseProfile(value) {
|
|
|
28479
29723
|
};
|
|
28480
29724
|
}
|
|
28481
29725
|
function readMachineProfile(deps = {}) {
|
|
28482
|
-
const value = readPrivate(
|
|
29726
|
+
const value = readPrivate(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
28483
29727
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
28484
29728
|
}
|
|
29729
|
+
var NETWORK_SECRET_AUTH = "network-secret";
|
|
29730
|
+
var NETWORK_TOKEN_AUTH = "network-token";
|
|
29731
|
+
var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
29732
|
+
var brokerKeys = /* @__PURE__ */ new Map();
|
|
29733
|
+
function networkSecretBrokerKey(deps, clientId) {
|
|
29734
|
+
const directory = configurationDirectory(deps);
|
|
29735
|
+
const path = join14(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
29736
|
+
const known = brokerKeys.get(path);
|
|
29737
|
+
if (known) return known;
|
|
29738
|
+
ensureDirectory(directory);
|
|
29739
|
+
const read = () => {
|
|
29740
|
+
try {
|
|
29741
|
+
const stat = lstatSync6(path);
|
|
29742
|
+
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
29743
|
+
throw new MachineAuthError(
|
|
29744
|
+
"unsafe_storage",
|
|
29745
|
+
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
29746
|
+
true
|
|
29747
|
+
);
|
|
29748
|
+
const value = readFileSync10(path, "utf8").trim();
|
|
29749
|
+
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
29750
|
+
} catch (error) {
|
|
29751
|
+
if (error.code === "ENOENT") return void 0;
|
|
29752
|
+
throw error;
|
|
29753
|
+
}
|
|
29754
|
+
};
|
|
29755
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
29756
|
+
const existing = read();
|
|
29757
|
+
if (existing?.key) {
|
|
29758
|
+
brokerKeys.set(path, existing.key);
|
|
29759
|
+
return existing.key;
|
|
29760
|
+
}
|
|
29761
|
+
if (existing)
|
|
29762
|
+
throw new MachineAuthError(
|
|
29763
|
+
"unsafe_storage",
|
|
29764
|
+
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
29765
|
+
true
|
|
29766
|
+
);
|
|
29767
|
+
const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
|
|
29768
|
+
try {
|
|
29769
|
+
writeFileSync5(staged, `${randomBytes4(32).toString("hex")}
|
|
29770
|
+
`, { mode: 384, flag: "wx" });
|
|
29771
|
+
protectPath(staged, false);
|
|
29772
|
+
linkSync(staged, path);
|
|
29773
|
+
} catch (error) {
|
|
29774
|
+
if (error.code !== "EEXIST") throw error;
|
|
29775
|
+
} finally {
|
|
29776
|
+
rmSync8(staged, { force: true });
|
|
29777
|
+
}
|
|
29778
|
+
}
|
|
29779
|
+
const key = read()?.key;
|
|
29780
|
+
if (!key)
|
|
29781
|
+
throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
|
|
29782
|
+
brokerKeys.set(path, key);
|
|
29783
|
+
return key;
|
|
29784
|
+
}
|
|
28485
29785
|
function environmentCredentials(deps) {
|
|
28486
29786
|
const env = deps.env ?? process.env;
|
|
28487
|
-
const {
|
|
28488
|
-
|
|
29787
|
+
const {
|
|
29788
|
+
PRIM_M2M_CLIENT_ID: clientId,
|
|
29789
|
+
PRIM_M2M_CLIENT_SECRET: clientSecret,
|
|
29790
|
+
PRIM_M2M_CLIENT_AUTH: auth
|
|
29791
|
+
} = env;
|
|
29792
|
+
if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
|
|
29793
|
+
if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
|
|
29794
|
+
throw new MachineAuthError(
|
|
29795
|
+
"incomplete_machine_credentials",
|
|
29796
|
+
`PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
|
|
29797
|
+
);
|
|
29798
|
+
if (auth !== void 0) {
|
|
29799
|
+
if (!clientId || !/^client_[\w-]+$/u.test(clientId))
|
|
29800
|
+
throw new MachineAuthError(
|
|
29801
|
+
"incomplete_machine_credentials",
|
|
29802
|
+
`Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
|
|
29803
|
+
);
|
|
29804
|
+
if (clientSecret !== void 0)
|
|
29805
|
+
throw new MachineAuthError(
|
|
29806
|
+
"conflicting_credentials",
|
|
29807
|
+
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
29808
|
+
);
|
|
29809
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
29810
|
+
const credentials = {
|
|
29811
|
+
clientId,
|
|
29812
|
+
generation,
|
|
29813
|
+
...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
|
|
29814
|
+
};
|
|
29815
|
+
Object.defineProperty(credentials, "clientSecret", {
|
|
29816
|
+
enumerable: true,
|
|
29817
|
+
get: () => networkSecretBrokerKey(deps, clientId)
|
|
29818
|
+
});
|
|
29819
|
+
return credentials;
|
|
29820
|
+
}
|
|
28489
29821
|
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
28490
29822
|
throw new MachineAuthError(
|
|
28491
29823
|
"incomplete_machine_credentials",
|
|
@@ -28495,12 +29827,12 @@ function environmentCredentials(deps) {
|
|
|
28495
29827
|
return {
|
|
28496
29828
|
clientId,
|
|
28497
29829
|
clientSecret,
|
|
28498
|
-
generation:
|
|
29830
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
28499
29831
|
};
|
|
28500
29832
|
}
|
|
28501
29833
|
function hasMachineConfiguration(deps = {}) {
|
|
28502
29834
|
const env = deps.env ?? process.env;
|
|
28503
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 ||
|
|
29835
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync10(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
28504
29836
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
28505
29837
|
throw new MachineAuthError(
|
|
28506
29838
|
"conflicting_credentials",
|
|
@@ -28512,6 +29844,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
28512
29844
|
}
|
|
28513
29845
|
function machineContext(deps = {}) {
|
|
28514
29846
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
29847
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
28515
29848
|
const environment = environmentCredentials(deps);
|
|
28516
29849
|
if (environment) {
|
|
28517
29850
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -28526,6 +29859,7 @@ function machineContext(deps = {}) {
|
|
|
28526
29859
|
return profile;
|
|
28527
29860
|
}
|
|
28528
29861
|
function cachedMachineCredential(deps = {}) {
|
|
29862
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
28529
29863
|
const context = machineContext(deps);
|
|
28530
29864
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
28531
29865
|
}
|
|
@@ -28534,9 +29868,11 @@ function machineSessionEnded(deps = {}) {
|
|
|
28534
29868
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
28535
29869
|
if (!generation) return false;
|
|
28536
29870
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
28537
|
-
return readPrivate(
|
|
29871
|
+
return readPrivate(join14(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
28538
29872
|
}
|
|
28539
29873
|
var environmentTerminal;
|
|
29874
|
+
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
29875
|
+
var networkRejection;
|
|
28540
29876
|
async function loadRecord(profile, deps, signal) {
|
|
28541
29877
|
const directory = configurationDirectory(deps);
|
|
28542
29878
|
let value;
|
|
@@ -28596,10 +29932,12 @@ async function persistRecord(record, deps, signal) {
|
|
|
28596
29932
|
}
|
|
28597
29933
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
28598
29934
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
29935
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
28599
29936
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
28600
29937
|
const apiUrl = apiUrlFor(deps);
|
|
28601
29938
|
const environment = environmentCredentials(deps);
|
|
28602
29939
|
if (environment) {
|
|
29940
|
+
const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
|
|
28603
29941
|
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
28604
29942
|
const directory2 = configurationDirectory(deps);
|
|
28605
29943
|
ensureDirectory(directory2);
|
|
@@ -28617,22 +29955,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28617
29955
|
writeEnvironmentContext(cached, deps);
|
|
28618
29956
|
return cached;
|
|
28619
29957
|
} catch (error) {
|
|
28620
|
-
if (error instanceof MachineAuthError && error.terminal)
|
|
29958
|
+
if (error instanceof MachineAuthError && error.terminal && !networkManaged)
|
|
28621
29959
|
environmentTerminal = environment.generation;
|
|
28622
29960
|
throw error;
|
|
28623
29961
|
}
|
|
28624
29962
|
}
|
|
28625
29963
|
return withFileLock(
|
|
28626
|
-
|
|
29964
|
+
join14(directory2, "credentials.lock"),
|
|
28627
29965
|
async () => {
|
|
28628
29966
|
if (machineSessionEnded(deps))
|
|
28629
29967
|
throw new MachineAuthError(
|
|
28630
29968
|
"machine_credentials_rejected",
|
|
28631
|
-
"Rotate the injected machine credentials.",
|
|
29969
|
+
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
28632
29970
|
true
|
|
28633
29971
|
);
|
|
28634
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
29972
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
28635
29973
|
return cached;
|
|
29974
|
+
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
29975
|
+
throw networkRejection.error;
|
|
28636
29976
|
try {
|
|
28637
29977
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
28638
29978
|
directory2,
|
|
@@ -28641,13 +29981,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28641
29981
|
signal,
|
|
28642
29982
|
async () => {
|
|
28643
29983
|
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
29984
|
+
if (environment.tokenInjection) {
|
|
29985
|
+
const identity3 = await verifyInjectedMachineIdentity(
|
|
29986
|
+
apiUrl,
|
|
29987
|
+
environment.clientId,
|
|
29988
|
+
signal,
|
|
29989
|
+
deps.fetch
|
|
29990
|
+
);
|
|
29991
|
+
const tokens3 = {
|
|
29992
|
+
accessToken: "",
|
|
29993
|
+
expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
|
|
29994
|
+
};
|
|
29995
|
+
return { configuration: configuration2, tokens: tokens3, identity: identity3 };
|
|
29996
|
+
}
|
|
28644
29997
|
const tokens2 = await exchangeMachineCredentials(
|
|
28645
29998
|
configuration2,
|
|
28646
29999
|
environment.clientId,
|
|
28647
|
-
|
|
30000
|
+
// The broker key is not a client secret; the proxy supplies that.
|
|
30001
|
+
environment.secretInjection ? "" : environment.clientSecret,
|
|
28648
30002
|
signal,
|
|
28649
|
-
deps.fetch
|
|
28650
|
-
|
|
30003
|
+
deps.fetch,
|
|
30004
|
+
{ secretInjection: environment.secretInjection }
|
|
30005
|
+
).catch((error) => {
|
|
30006
|
+
if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
|
|
30007
|
+
throw new MachineAuthError(
|
|
30008
|
+
"network_secret_mismatch",
|
|
30009
|
+
`The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
|
|
30010
|
+
true
|
|
30011
|
+
);
|
|
30012
|
+
throw error;
|
|
30013
|
+
});
|
|
28651
30014
|
const identity2 = await verifyMachineIdentity(
|
|
28652
30015
|
apiUrl,
|
|
28653
30016
|
tokens2.accessToken,
|
|
@@ -28664,17 +30027,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28664
30027
|
...identity,
|
|
28665
30028
|
apiUrl,
|
|
28666
30029
|
generation: environment.generation,
|
|
28667
|
-
storage: "environment"
|
|
30030
|
+
storage: "environment",
|
|
30031
|
+
...environment.tokenInjection ? { tokenInjection: "network" } : {}
|
|
28668
30032
|
};
|
|
28669
30033
|
writeEnvironmentContext(cached, deps);
|
|
28670
30034
|
return cached;
|
|
28671
30035
|
} catch (error) {
|
|
30036
|
+
if (networkManaged && error instanceof MachineAuthError && error.terminal) {
|
|
30037
|
+
networkRejection = {
|
|
30038
|
+
generation: environment.generation,
|
|
30039
|
+
until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
|
|
30040
|
+
error
|
|
30041
|
+
};
|
|
30042
|
+
if (cached?.generation === environment.generation) cached = void 0;
|
|
30043
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
30044
|
+
try {
|
|
30045
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
30046
|
+
rmSync8(contextPath, { force: true });
|
|
30047
|
+
} catch {
|
|
30048
|
+
}
|
|
30049
|
+
throw error;
|
|
30050
|
+
}
|
|
28672
30051
|
if (error instanceof MachineAuthError && error.terminal) {
|
|
28673
30052
|
environmentTerminal = environment.generation;
|
|
28674
30053
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
28675
30054
|
try {
|
|
28676
30055
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
28677
|
-
|
|
30056
|
+
rmSync8(contextPath, { force: true });
|
|
28678
30057
|
} catch {
|
|
28679
30058
|
}
|
|
28680
30059
|
}
|
|
@@ -28688,7 +30067,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28688
30067
|
const expected = machineContext(deps);
|
|
28689
30068
|
const directory = configurationDirectory(deps);
|
|
28690
30069
|
return withFileLock(
|
|
28691
|
-
|
|
30070
|
+
join14(directory, "credentials.lock"),
|
|
28692
30071
|
async () => {
|
|
28693
30072
|
const profile = readMachineProfile(deps);
|
|
28694
30073
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -28703,7 +30082,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28703
30082
|
true
|
|
28704
30083
|
);
|
|
28705
30084
|
let record = await loadRecord(profile, deps, signal);
|
|
28706
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
30085
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
28707
30086
|
try {
|
|
28708
30087
|
const { tokens, identity } = await withMachineCooldown(
|
|
28709
30088
|
directory,
|
|
@@ -28738,7 +30117,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28738
30117
|
await persistRecord(record, deps, signal);
|
|
28739
30118
|
} catch (error) {
|
|
28740
30119
|
if (error instanceof MachineAuthError && error.terminal)
|
|
28741
|
-
writePrivate(
|
|
30120
|
+
writePrivate(join14(directory, "machine_terminal.json"), profile.generation);
|
|
28742
30121
|
throw error;
|
|
28743
30122
|
}
|
|
28744
30123
|
}
|
|
@@ -28749,23 +30128,47 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28749
30128
|
{ signal }
|
|
28750
30129
|
);
|
|
28751
30130
|
}
|
|
30131
|
+
async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
30132
|
+
const environment = environmentCredentials(deps);
|
|
30133
|
+
if (!environment?.tokenInjection)
|
|
30134
|
+
throw new MachineAuthError(
|
|
30135
|
+
"identity_changed",
|
|
30136
|
+
"Machine identity changed; restart the operation."
|
|
30137
|
+
);
|
|
30138
|
+
const directory = configurationDirectory(deps);
|
|
30139
|
+
ensureDirectory(directory);
|
|
30140
|
+
return forwardBrokerRequest({
|
|
30141
|
+
directory,
|
|
30142
|
+
apiUrl: apiUrlFor(deps),
|
|
30143
|
+
environment,
|
|
30144
|
+
env: deps.env ?? process.env,
|
|
30145
|
+
request: request3,
|
|
30146
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
30147
|
+
});
|
|
30148
|
+
}
|
|
30149
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
30150
|
+
ensureDirectory(directory);
|
|
30151
|
+
}
|
|
30152
|
+
function writeMachineMetadata(path, value) {
|
|
30153
|
+
writePrivate(path, value);
|
|
30154
|
+
}
|
|
28752
30155
|
|
|
28753
30156
|
// src/lib/credentials.ts
|
|
28754
30157
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
28755
|
-
var TOKEN_FILE_PATH =
|
|
28756
|
-
var REFRESH_TOKEN_PATH =
|
|
28757
|
-
var TOKEN_EXPIRES_PATH =
|
|
28758
|
-
var TERMINAL_REFRESH_PATH =
|
|
28759
|
-
var CREDENTIAL_METADATA_PATH =
|
|
28760
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
28761
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
28762
|
-
var CREDENTIAL_LOCK_PATH =
|
|
30158
|
+
var TOKEN_FILE_PATH = join15(CONFIG_DIRECTORY, "token");
|
|
30159
|
+
var REFRESH_TOKEN_PATH = join15(CONFIG_DIRECTORY, "refresh_token");
|
|
30160
|
+
var TOKEN_EXPIRES_PATH = join15(CONFIG_DIRECTORY, "token_expires_at");
|
|
30161
|
+
var TERMINAL_REFRESH_PATH = join15(CONFIG_DIRECTORY, "refresh_terminal");
|
|
30162
|
+
var CREDENTIAL_METADATA_PATH = join15(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
30163
|
+
var CREDENTIAL_FAMILY_PATH = join15(CONFIG_DIRECTORY, "credential_family.json");
|
|
30164
|
+
var CREDENTIAL_MIGRATION_PATH = join15(CONFIG_DIRECTORY, "credential_migration.json");
|
|
30165
|
+
var CREDENTIAL_LOCK_PATH = join15(CONFIG_DIRECTORY, "credentials.lock");
|
|
28763
30166
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
28764
30167
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
28765
30168
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
28766
30169
|
function readTrimmed(path) {
|
|
28767
30170
|
try {
|
|
28768
|
-
const value =
|
|
30171
|
+
const value = readFileSync11(path, "utf8").trim();
|
|
28769
30172
|
return value || void 0;
|
|
28770
30173
|
} catch {
|
|
28771
30174
|
return void 0;
|
|
@@ -28774,7 +30177,7 @@ function readTrimmed(path) {
|
|
|
28774
30177
|
function resolveAuthCredential(options = {}) {
|
|
28775
30178
|
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
28776
30179
|
const machine = cachedMachineCredential({ env: options.env });
|
|
28777
|
-
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
30180
|
+
return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
28778
30181
|
}
|
|
28779
30182
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
28780
30183
|
if (envToken) return { token: envToken, source: "environment" };
|
|
@@ -28787,22 +30190,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
28787
30190
|
);
|
|
28788
30191
|
if (metadata.state === "legacy_broker") {
|
|
28789
30192
|
if (metadata.metadata) {
|
|
28790
|
-
const
|
|
28791
|
-
if (!
|
|
30193
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
30194
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
28792
30195
|
return void 0;
|
|
28793
30196
|
}
|
|
28794
30197
|
}
|
|
28795
30198
|
return { token: stored, source: "token_file" };
|
|
28796
30199
|
}
|
|
28797
30200
|
if (metadata.state === "invalid") return void 0;
|
|
28798
|
-
const
|
|
28799
|
-
if (!
|
|
30201
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
30202
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
28800
30203
|
return void 0;
|
|
28801
30204
|
}
|
|
28802
30205
|
return { token: stored, source: "token_file" };
|
|
28803
30206
|
}
|
|
28804
30207
|
function credentialFingerprint(value) {
|
|
28805
|
-
return
|
|
30208
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
28806
30209
|
}
|
|
28807
30210
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
28808
30211
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -28822,7 +30225,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
28822
30225
|
function readBoundedCredentialJson(path) {
|
|
28823
30226
|
let raw;
|
|
28824
30227
|
try {
|
|
28825
|
-
raw =
|
|
30228
|
+
raw = readFileSync11(path, "utf8");
|
|
28826
30229
|
} catch (error) {
|
|
28827
30230
|
return error.code === "ENOENT" ? void 0 : null;
|
|
28828
30231
|
}
|
|
@@ -28894,9 +30297,9 @@ function jwtExpiresAt(token) {
|
|
|
28894
30297
|
}
|
|
28895
30298
|
|
|
28896
30299
|
// src/daemon/client-instance-id.ts
|
|
28897
|
-
import { randomBytes as
|
|
28898
|
-
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as
|
|
28899
|
-
import { join as
|
|
30300
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
30301
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync12 } from "fs";
|
|
30302
|
+
import { join as join16 } from "path";
|
|
28900
30303
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
28901
30304
|
var INSTANCE_FILE_MODE = 384;
|
|
28902
30305
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -28933,7 +30336,7 @@ function readExisting(path) {
|
|
|
28933
30336
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
28934
30337
|
throw new Error("stored client instance identity is invalid");
|
|
28935
30338
|
}
|
|
28936
|
-
const raw =
|
|
30339
|
+
const raw = readFileSync12(path, "utf8");
|
|
28937
30340
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
28938
30341
|
if (raw !== value && raw !== `${value}
|
|
28939
30342
|
` || !isClientInstanceId(value)) {
|
|
@@ -28947,8 +30350,8 @@ function atomicWrite(path, value) {
|
|
|
28947
30350
|
}
|
|
28948
30351
|
async function getOrCreateClientInstanceId(options) {
|
|
28949
30352
|
const configDir = options.configDir;
|
|
28950
|
-
const path =
|
|
28951
|
-
const lockPath =
|
|
30353
|
+
const path = join16(configDir, "client_instance_id");
|
|
30354
|
+
const lockPath = join16(configDir, "client-instance.lock");
|
|
28952
30355
|
ensurePrivateConfigDirectory(configDir);
|
|
28953
30356
|
return withFileLock(
|
|
28954
30357
|
lockPath,
|
|
@@ -28957,7 +30360,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
28957
30360
|
if (existing !== void 0) {
|
|
28958
30361
|
return existing;
|
|
28959
30362
|
}
|
|
28960
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
30363
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
28961
30364
|
"base64url"
|
|
28962
30365
|
)}`;
|
|
28963
30366
|
if (!isClientInstanceId(generated)) {
|
|
@@ -28992,56 +30395,18 @@ async function ingestUploaderHeaders() {
|
|
|
28992
30395
|
return headers;
|
|
28993
30396
|
}
|
|
28994
30397
|
|
|
28995
|
-
// src/lib/terminal-safe.ts
|
|
28996
|
-
function replaceIsolatedSurrogates(value) {
|
|
28997
|
-
let out = "";
|
|
28998
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
28999
|
-
const unit = value.charCodeAt(index);
|
|
29000
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
29001
|
-
const next = value.charCodeAt(index + 1);
|
|
29002
|
-
if (next >= 56320 && next <= 57343) {
|
|
29003
|
-
out += value[index] + value[index + 1];
|
|
29004
|
-
index += 1;
|
|
29005
|
-
} else {
|
|
29006
|
-
out += "\uFFFD";
|
|
29007
|
-
}
|
|
29008
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
29009
|
-
out += "\uFFFD";
|
|
29010
|
-
} else {
|
|
29011
|
-
out += value[index];
|
|
29012
|
-
}
|
|
29013
|
-
}
|
|
29014
|
-
return out;
|
|
29015
|
-
}
|
|
29016
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
29017
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
29018
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
29019
|
-
point === 1564 || // Arabic letter mark
|
|
29020
|
-
point === 6158 || // Mongolian vowel separator
|
|
29021
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
29022
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
29023
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
29024
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
29025
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
29026
|
-
point >= 917504 && point <= 917631;
|
|
29027
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
29028
|
-
}
|
|
29029
|
-
function terminalSafeText(value) {
|
|
29030
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
29031
|
-
}
|
|
29032
|
-
function terminalSafeLine(value) {
|
|
29033
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
29034
|
-
}
|
|
29035
|
-
|
|
29036
30398
|
// src/client.ts
|
|
29037
30399
|
var CONFIG_DIR_MODE = 448;
|
|
29038
30400
|
var CREDENTIAL_FILE_MODE = 384;
|
|
29039
30401
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
29040
|
-
var
|
|
30402
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
29041
30403
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
30404
|
+
function authExpiredMessage() {
|
|
30405
|
+
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
30406
|
+
}
|
|
29042
30407
|
function readTrimmed2(path) {
|
|
29043
30408
|
try {
|
|
29044
|
-
const value =
|
|
30409
|
+
const value = readFileSync13(path, "utf8").trim();
|
|
29045
30410
|
return value || void 0;
|
|
29046
30411
|
} catch {
|
|
29047
30412
|
return void 0;
|
|
@@ -29051,14 +30416,14 @@ function getSiteUrl() {
|
|
|
29051
30416
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
29052
30417
|
}
|
|
29053
30418
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
29054
|
-
return primApiUrl?.trim() ||
|
|
30419
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
29055
30420
|
}
|
|
29056
30421
|
function expiresAtFor(token, expiresIn) {
|
|
29057
30422
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
29058
30423
|
}
|
|
29059
30424
|
function ensureConfigDirectory() {
|
|
29060
30425
|
const directory = dirname8(TOKEN_FILE_PATH);
|
|
29061
|
-
|
|
30426
|
+
mkdirSync6(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
29062
30427
|
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
29063
30428
|
}
|
|
29064
30429
|
function atomicWrite2(path, content2) {
|
|
@@ -29066,8 +30431,8 @@ function atomicWrite2(path, content2) {
|
|
|
29066
30431
|
atomicWriteFile(path, content2, { mode: CREDENTIAL_FILE_MODE });
|
|
29067
30432
|
}
|
|
29068
30433
|
function removeCredentialFile(path) {
|
|
29069
|
-
if (!
|
|
29070
|
-
|
|
30434
|
+
if (!existsSync11(path)) return false;
|
|
30435
|
+
rmSync9(path, { force: true });
|
|
29071
30436
|
return true;
|
|
29072
30437
|
}
|
|
29073
30438
|
function getTokenExpiresAt() {
|
|
@@ -29082,23 +30447,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
29082
30447
|
const expiresAt = getTokenExpiresAt();
|
|
29083
30448
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
29084
30449
|
}
|
|
29085
|
-
function refreshFingerprint(
|
|
29086
|
-
return
|
|
30450
|
+
function refreshFingerprint(refreshToken3) {
|
|
30451
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
29087
30452
|
}
|
|
29088
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
30453
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
29089
30454
|
return {
|
|
29090
30455
|
version: 1,
|
|
29091
30456
|
family: "legacy_broker",
|
|
29092
30457
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29093
|
-
refreshTokenHash: refreshFingerprint(
|
|
30458
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29094
30459
|
};
|
|
29095
30460
|
}
|
|
29096
|
-
function credentialFamilyMetadata(accessToken,
|
|
30461
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
29097
30462
|
const hashes = {
|
|
29098
30463
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29099
|
-
refreshTokenHash: refreshFingerprint(
|
|
30464
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29100
30465
|
};
|
|
29101
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
30466
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
29102
30467
|
}
|
|
29103
30468
|
function writeCredentialMigrationSentinel() {
|
|
29104
30469
|
atomicWrite2(
|
|
@@ -29110,11 +30475,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
29110
30475
|
`
|
|
29111
30476
|
);
|
|
29112
30477
|
}
|
|
29113
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
29114
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
30478
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
30479
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
29115
30480
|
return { state: "invalid" };
|
|
29116
30481
|
}
|
|
29117
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30482
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29118
30483
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
29119
30484
|
return { state: "invalid" };
|
|
29120
30485
|
}
|
|
@@ -29131,17 +30496,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
29131
30496
|
const metadata = readStoredCredentialMetadata();
|
|
29132
30497
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
29133
30498
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
29134
|
-
const
|
|
29135
|
-
if (!(accessToken &&
|
|
29136
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30499
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
30500
|
+
if (!(accessToken && refreshToken3)) return;
|
|
30501
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29137
30502
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29138
30503
|
`);
|
|
29139
30504
|
}
|
|
29140
30505
|
function terminalFingerprint() {
|
|
29141
30506
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
29142
30507
|
}
|
|
29143
|
-
function writeTerminalFingerprint(
|
|
29144
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
30508
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
30509
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
29145
30510
|
`);
|
|
29146
30511
|
}
|
|
29147
30512
|
function clearTerminalFingerprint() {
|
|
@@ -29150,20 +30515,20 @@ function clearTerminalFingerprint() {
|
|
|
29150
30515
|
function isSessionEnded() {
|
|
29151
30516
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
29152
30517
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
29153
|
-
const
|
|
30518
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
29154
30519
|
const ended = terminalFingerprint();
|
|
29155
|
-
return Boolean(
|
|
30520
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
29156
30521
|
}
|
|
29157
30522
|
function withCredentialLock(operation, options = {}) {
|
|
29158
30523
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
29159
30524
|
}
|
|
29160
30525
|
function commitCredentialsUnlocked(credentials) {
|
|
29161
30526
|
const accessToken = credentials.accessToken.trim();
|
|
29162
|
-
const
|
|
29163
|
-
if (!accessToken || !
|
|
30527
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
30528
|
+
if (!accessToken || !refreshToken3) {
|
|
29164
30529
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
29165
30530
|
}
|
|
29166
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
30531
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
29167
30532
|
if (credentials.metadata !== void 0) {
|
|
29168
30533
|
preserveMarkerlessLegacyGeneration();
|
|
29169
30534
|
writeCredentialMigrationSentinel();
|
|
@@ -29171,10 +30536,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
29171
30536
|
`);
|
|
29172
30537
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
29173
30538
|
`);
|
|
29174
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30539
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29175
30540
|
`);
|
|
29176
30541
|
} else {
|
|
29177
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30542
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29178
30543
|
`);
|
|
29179
30544
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29180
30545
|
`);
|
|
@@ -29211,15 +30576,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
29211
30576
|
`
|
|
29212
30577
|
);
|
|
29213
30578
|
}
|
|
29214
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
30579
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
29215
30580
|
const current = readStoredCredentialMetadata();
|
|
29216
30581
|
if (expected.state === "legacy_broker") {
|
|
29217
30582
|
if (current.state !== "legacy_broker") return false;
|
|
29218
30583
|
if (!expected.metadata) return current.metadata === void 0;
|
|
29219
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
30584
|
+
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
29220
30585
|
}
|
|
29221
30586
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
29222
|
-
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
30587
|
+
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
29223
30588
|
}
|
|
29224
30589
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
29225
30590
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -29388,7 +30753,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
29388
30753
|
);
|
|
29389
30754
|
}
|
|
29390
30755
|
var _refreshInFlight;
|
|
29391
|
-
function
|
|
30756
|
+
function refreshToken2(options = {}) {
|
|
29392
30757
|
if (hasMachineConfiguration())
|
|
29393
30758
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
29394
30759
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -29420,7 +30785,7 @@ var CliManagementResponseError = class extends Error {
|
|
|
29420
30785
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
29421
30786
|
async function managementResponseValue(response) {
|
|
29422
30787
|
if (response.status === 401) {
|
|
29423
|
-
throw new HttpError(401,
|
|
30788
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29424
30789
|
}
|
|
29425
30790
|
let value;
|
|
29426
30791
|
try {
|
|
@@ -29442,23 +30807,50 @@ function selectedCredential() {
|
|
|
29442
30807
|
}
|
|
29443
30808
|
return _cachedCredential;
|
|
29444
30809
|
}
|
|
30810
|
+
async function requestHeaders(method, path) {
|
|
30811
|
+
return {
|
|
30812
|
+
"Content-Type": "application/json",
|
|
30813
|
+
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
30814
|
+
};
|
|
30815
|
+
}
|
|
29445
30816
|
async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
29446
30817
|
return fetch(`${siteUrl}${path}`, {
|
|
29447
30818
|
method,
|
|
29448
|
-
headers: {
|
|
29449
|
-
Authorization: `Bearer ${token}`,
|
|
29450
|
-
"Content-Type": "application/json",
|
|
29451
|
-
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
29452
|
-
},
|
|
30819
|
+
headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
|
|
29453
30820
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
29454
30821
|
signal: options?.signal,
|
|
29455
30822
|
redirect: options?.redirect
|
|
29456
30823
|
});
|
|
29457
30824
|
}
|
|
30825
|
+
async function fetchAsMachine(credential, method, path, body, options) {
|
|
30826
|
+
if (!credential.tokenInjection)
|
|
30827
|
+
return fetchWithToken(
|
|
30828
|
+
method,
|
|
30829
|
+
path,
|
|
30830
|
+
body,
|
|
30831
|
+
{ ...options, redirect: "error" },
|
|
30832
|
+
credential.accessToken,
|
|
30833
|
+
credential.apiUrl
|
|
30834
|
+
);
|
|
30835
|
+
try {
|
|
30836
|
+
return await forwardMachineRequest(
|
|
30837
|
+
{
|
|
30838
|
+
method,
|
|
30839
|
+
path,
|
|
30840
|
+
headers: await requestHeaders(method, path),
|
|
30841
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
30842
|
+
},
|
|
30843
|
+
options.signal
|
|
30844
|
+
);
|
|
30845
|
+
} catch (error) {
|
|
30846
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
30847
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
30848
|
+
}
|
|
30849
|
+
}
|
|
29458
30850
|
async function responseValue(response) {
|
|
29459
30851
|
if (!response.ok) {
|
|
29460
30852
|
if (response.status === 401) {
|
|
29461
|
-
throw new HttpError(401,
|
|
30853
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29462
30854
|
}
|
|
29463
30855
|
const errorBody = await response.json().catch(() => null);
|
|
29464
30856
|
const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
|
|
@@ -29485,14 +30877,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29485
30877
|
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
29486
30878
|
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
29487
30879
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
29488
|
-
let response = await
|
|
29489
|
-
method,
|
|
29490
|
-
path,
|
|
29491
|
-
body,
|
|
29492
|
-
{ ...requestOptions, redirect: "error" },
|
|
29493
|
-
current.accessToken,
|
|
29494
|
-
selected.apiUrl
|
|
29495
|
-
);
|
|
30880
|
+
let response = await fetchAsMachine(current, method, path, body, requestOptions);
|
|
29496
30881
|
if (response.status === 401) {
|
|
29497
30882
|
const renewed = await acquireMachineCredential({
|
|
29498
30883
|
force: true,
|
|
@@ -29501,19 +30886,14 @@ async function machineClient(options = {}, management = false) {
|
|
|
29501
30886
|
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
29502
30887
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
29503
30888
|
}
|
|
29504
|
-
response = await
|
|
29505
|
-
method,
|
|
29506
|
-
path,
|
|
29507
|
-
body,
|
|
29508
|
-
{ ...requestOptions, redirect: "error" },
|
|
29509
|
-
renewed.accessToken,
|
|
29510
|
-
renewed.apiUrl
|
|
29511
|
-
);
|
|
30889
|
+
response = await fetchAsMachine(renewed, method, path, body, requestOptions);
|
|
29512
30890
|
}
|
|
29513
30891
|
if (response.status === 401)
|
|
29514
30892
|
throw new HttpError(
|
|
29515
30893
|
401,
|
|
29516
|
-
"Machine access was rejected.
|
|
30894
|
+
selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
30895
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
30896
|
+
)
|
|
29517
30897
|
);
|
|
29518
30898
|
return parse2(response);
|
|
29519
30899
|
};
|
|
@@ -29523,7 +30903,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29523
30903
|
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
29524
30904
|
};
|
|
29525
30905
|
}
|
|
29526
|
-
async function
|
|
30906
|
+
async function request2(method, path, body, options) {
|
|
29527
30907
|
const machine = await machineClient(options);
|
|
29528
30908
|
if (machine)
|
|
29529
30909
|
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
@@ -29532,17 +30912,17 @@ async function request(method, path, body, options) {
|
|
|
29532
30912
|
let refreshAttempted = false;
|
|
29533
30913
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
29534
30914
|
refreshAttempted = true;
|
|
29535
|
-
const token = await
|
|
30915
|
+
const token = await refreshToken2({
|
|
29536
30916
|
signal: options?.signal,
|
|
29537
30917
|
quiet: options?.quietRefresh
|
|
29538
30918
|
});
|
|
29539
30919
|
if (token) credential = { token, source: "token_file" };
|
|
29540
30920
|
}
|
|
29541
30921
|
if (!credential) {
|
|
29542
|
-
throw new HttpError(401,
|
|
30922
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29543
30923
|
}
|
|
29544
30924
|
if (isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
29545
|
-
throw new HttpError(401,
|
|
30925
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29546
30926
|
}
|
|
29547
30927
|
const tokenUsed = credential.token;
|
|
29548
30928
|
let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
|
|
@@ -29551,7 +30931,7 @@ async function request(method, path, body, options) {
|
|
|
29551
30931
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
29552
30932
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
29553
30933
|
refreshAttempted = true;
|
|
29554
|
-
retryToken = await
|
|
30934
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
29555
30935
|
}
|
|
29556
30936
|
if (retryToken) {
|
|
29557
30937
|
_cachedCredential = {
|
|
@@ -29565,8 +30945,8 @@ async function request(method, path, body, options) {
|
|
|
29565
30945
|
}
|
|
29566
30946
|
function getClient() {
|
|
29567
30947
|
return {
|
|
29568
|
-
get: (path, options) =>
|
|
29569
|
-
post: (path, body, options) =>
|
|
30948
|
+
get: (path, options) => request2("GET", path, void 0, options),
|
|
30949
|
+
post: (path, body, options) => request2("POST", path, body, options)
|
|
29570
30950
|
};
|
|
29571
30951
|
}
|
|
29572
30952
|
|
|
@@ -29868,8 +31248,8 @@ function parseAgent(argv) {
|
|
|
29868
31248
|
}
|
|
29869
31249
|
|
|
29870
31250
|
// src/hooks/redact.ts
|
|
29871
|
-
import { existsSync as
|
|
29872
|
-
import { join as
|
|
31251
|
+
import { existsSync as existsSync12, readFileSync as readFileSync14, statSync as statSync3 } from "fs";
|
|
31252
|
+
import { join as join18 } from "path";
|
|
29873
31253
|
import { Worker } from "worker_threads";
|
|
29874
31254
|
|
|
29875
31255
|
// src/lib/ansi.ts
|
|
@@ -29924,6 +31304,11 @@ var DEFAULT_RULES = [
|
|
|
29924
31304
|
pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
|
|
29925
31305
|
reason: "aws-secret"
|
|
29926
31306
|
},
|
|
31307
|
+
{
|
|
31308
|
+
// `prim auth enroll --print-env` output an agent may write into a file.
|
|
31309
|
+
pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
|
|
31310
|
+
reason: "prim-m2m-secret"
|
|
31311
|
+
},
|
|
29927
31312
|
{ pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
|
|
29928
31313
|
{
|
|
29929
31314
|
pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
|
|
@@ -30048,9 +31433,14 @@ function decisionLabel(conflict) {
|
|
|
30048
31433
|
const title = typeof conflict.title === "string" ? displayText(conflict.title, MAX_TITLE_CHARS) : "";
|
|
30049
31434
|
return title ? `Decision ${id2}: \u201C${title}\u201D.` : `Decision ${id2}: details unavailable; inspect it before approving.`;
|
|
30050
31435
|
}
|
|
31436
|
+
function isEmptyCheck(check) {
|
|
31437
|
+
const coverage = check.evaluationCoverage;
|
|
31438
|
+
return coverage?.status === "not_run" && coverage.candidateCount === 0 && (check.verdict === "allow" || check.verdict === "warn") && check.conflicts.length === 0;
|
|
31439
|
+
}
|
|
30051
31440
|
function incomplete(evidence) {
|
|
30052
31441
|
const coverage = evidence.evaluationCoverage;
|
|
30053
|
-
|
|
31442
|
+
const settled = coverage?.status === void 0 || coverage.status === "completed" || isEmptyCheck(evidence);
|
|
31443
|
+
return Array.isArray(coverage?.selectionOmissions) && coverage.selectionOmissions.length > 0 || Array.isArray(coverage?.evidenceOmissions) && coverage.evidenceOmissions.length > 0 || !settled || ["candidate_set_truncated", "evidence_incomplete", "coverage_unverified"].includes(
|
|
30054
31444
|
evidence.reasonCode
|
|
30055
31445
|
);
|
|
30056
31446
|
}
|
|
@@ -30073,17 +31463,17 @@ function approvalSummary(evidence, preview) {
|
|
|
30073
31463
|
}
|
|
30074
31464
|
|
|
30075
31465
|
// src/commands/cursor-install.ts
|
|
30076
|
-
import { existsSync as
|
|
31466
|
+
import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
|
|
30077
31467
|
import { homedir as homedir4 } from "os";
|
|
30078
|
-
import { isAbsolute as isAbsolute5, join as
|
|
31468
|
+
import { isAbsolute as isAbsolute5, join as join20 } from "path";
|
|
30079
31469
|
|
|
30080
31470
|
// src/lib/preflight-host.ts
|
|
30081
31471
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
30082
31472
|
|
|
30083
31473
|
// src/commands/claude-install.ts
|
|
30084
|
-
import { existsSync as
|
|
31474
|
+
import { existsSync as existsSync13, lstatSync as lstatSync8, readFileSync as readFileSync15 } from "fs";
|
|
30085
31475
|
import { homedir as homedir3 } from "os";
|
|
30086
|
-
import { join as
|
|
31476
|
+
import { join as join19 } from "path";
|
|
30087
31477
|
var CAPTURE_BIN = "prim-hook";
|
|
30088
31478
|
var GATE_BIN = "prim-pre-tool-use";
|
|
30089
31479
|
var POST_TOOL_USE_BIN = "prim-post-tool-use";
|
|
@@ -30092,7 +31482,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
30092
31482
|
var STATUSLINE_BIN = "prim-statusline";
|
|
30093
31483
|
var STATUSLINE_ARGS = "";
|
|
30094
31484
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
30095
|
-
var USER_SCOPE_PATH =
|
|
31485
|
+
var USER_SCOPE_PATH = join19(homedir3(), ".claude", "settings.json");
|
|
30096
31486
|
function projectRoot() {
|
|
30097
31487
|
return gitToplevel() ?? process.cwd();
|
|
30098
31488
|
}
|
|
@@ -30172,20 +31562,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
|
|
|
30172
31562
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
30173
31563
|
if (explicit && isAbsolute5(explicit)) return explicit;
|
|
30174
31564
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
30175
|
-
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return
|
|
30176
|
-
return
|
|
31565
|
+
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join20(xdg, "cursor");
|
|
31566
|
+
return join20(home, ".cursor");
|
|
30177
31567
|
}
|
|
30178
31568
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
30179
|
-
return scope === "user" ?
|
|
31569
|
+
return scope === "user" ? join20(cursorConfigDirectory(), "hooks.json") : join20(root, ".cursor", "hooks.json");
|
|
30180
31570
|
}
|
|
30181
31571
|
function plainObject(value) {
|
|
30182
31572
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
30183
31573
|
}
|
|
30184
31574
|
function readCursorHooks(path) {
|
|
30185
|
-
if (!
|
|
31575
|
+
if (!existsSync14(path)) return {};
|
|
30186
31576
|
let parsed;
|
|
30187
31577
|
try {
|
|
30188
|
-
parsed = JSON.parse(
|
|
31578
|
+
parsed = JSON.parse(readFileSync16(path, "utf8"));
|
|
30189
31579
|
} catch {
|
|
30190
31580
|
throw new Error(`invalid Cursor hooks JSON at ${path}`);
|
|
30191
31581
|
}
|
|
@@ -30328,7 +31718,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
|
|
|
30328
31718
|
}
|
|
30329
31719
|
|
|
30330
31720
|
// src/hooks/normalize.ts
|
|
30331
|
-
import { createHash as
|
|
31721
|
+
import { createHash as createHash10 } from "crypto";
|
|
30332
31722
|
import { realpathSync as realpathSync3 } from "fs";
|
|
30333
31723
|
import { isAbsolute as isAbsolute6, resolve as resolve5 } from "path";
|
|
30334
31724
|
var HERMES_EVENT_MAP = {
|
|
@@ -30373,7 +31763,7 @@ function requiredId(value, field) {
|
|
|
30373
31763
|
}
|
|
30374
31764
|
function cursorToolUseId(value) {
|
|
30375
31765
|
if (SAFE_CORRELATION_ID_RE.test(value)) return value;
|
|
30376
|
-
return `cursor:tool:v1:${
|
|
31766
|
+
return `cursor:tool:v1:${createHash10("sha256").update(value).digest("hex")}`;
|
|
30377
31767
|
}
|
|
30378
31768
|
function workspaceCandidates(value) {
|
|
30379
31769
|
if (!Array.isArray(value)) return [];
|
|
@@ -30470,7 +31860,7 @@ function normalizeEnvelope(parsed, agent2) {
|
|
|
30470
31860
|
]);
|
|
30471
31861
|
return {
|
|
30472
31862
|
...parsed,
|
|
30473
|
-
tool_use_id: `codex:fallback:v1:${
|
|
31863
|
+
tool_use_id: `codex:fallback:v1:${createHash10("sha256").update(stableToolIdentity).digest("hex")}`
|
|
30474
31864
|
};
|
|
30475
31865
|
}
|
|
30476
31866
|
return parsed;
|
|
@@ -36938,7 +38328,7 @@ var TokenGroup = class {
|
|
|
36938
38328
|
}
|
|
36939
38329
|
token(input, stack) {
|
|
36940
38330
|
let { parser: parser3 } = stack.p;
|
|
36941
|
-
|
|
38331
|
+
readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
|
|
36942
38332
|
}
|
|
36943
38333
|
};
|
|
36944
38334
|
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
|
|
@@ -36952,7 +38342,7 @@ var LocalTokenGroup = class {
|
|
|
36952
38342
|
let start = input.pos, skipped = 0;
|
|
36953
38343
|
for (; ; ) {
|
|
36954
38344
|
let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
|
|
36955
|
-
|
|
38345
|
+
readToken2(this.data, input, stack, 0, this.data, this.precTable);
|
|
36956
38346
|
if (input.token.value > -1)
|
|
36957
38347
|
break;
|
|
36958
38348
|
if (this.elseToken == null)
|
|
@@ -36985,7 +38375,7 @@ var ExternalTokenizer = class {
|
|
|
36985
38375
|
this.extend = !!options.extend;
|
|
36986
38376
|
}
|
|
36987
38377
|
};
|
|
36988
|
-
function
|
|
38378
|
+
function readToken2(data, input, stack, group, precTable, precOffset) {
|
|
36989
38379
|
let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
|
|
36990
38380
|
scan: for (; ; ) {
|
|
36991
38381
|
if ((groupMask & data[state]) == 0)
|
|
@@ -38798,7 +40188,7 @@ var newline2 = 10;
|
|
|
38798
40188
|
var carriageReturn = 13;
|
|
38799
40189
|
var space2 = 32;
|
|
38800
40190
|
var tab = 9;
|
|
38801
|
-
var
|
|
40191
|
+
var hash3 = 35;
|
|
38802
40192
|
var parenOpen = 40;
|
|
38803
40193
|
var dot2 = 46;
|
|
38804
40194
|
var braceOpen = 123;
|
|
@@ -38851,7 +40241,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
|
|
|
38851
40241
|
input.advance();
|
|
38852
40242
|
spaces2++;
|
|
38853
40243
|
}
|
|
38854
|
-
if (input.next == newline2 || input.next == carriageReturn || input.next ==
|
|
40244
|
+
if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
|
|
38855
40245
|
input.acceptToken(blankLineStart, -spaces2);
|
|
38856
40246
|
} else if (isLineBreak(input.next)) {
|
|
38857
40247
|
input.acceptToken(newline$1, 1);
|
|
@@ -38870,7 +40260,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
|
|
|
38870
40260
|
input.advance();
|
|
38871
40261
|
chars++;
|
|
38872
40262
|
}
|
|
38873
|
-
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next !=
|
|
40263
|
+
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
|
|
38874
40264
|
if (depth < context.indent) input.acceptToken(dedent, -chars);
|
|
38875
40265
|
else input.acceptToken(indent);
|
|
38876
40266
|
}
|
|
@@ -38944,7 +40334,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
|
|
|
38944
40334
|
for (let off = 0; ; off++) {
|
|
38945
40335
|
let next = input.peek(off);
|
|
38946
40336
|
if (next == space2 || next == tab) continue;
|
|
38947
|
-
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next !=
|
|
40337
|
+
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
|
|
38948
40338
|
input.acceptToken(printKeyword);
|
|
38949
40339
|
return;
|
|
38950
40340
|
}
|
|
@@ -40105,8 +41495,8 @@ function parsePreflightResponse(value) {
|
|
|
40105
41495
|
function decisionDisclosureContext(response) {
|
|
40106
41496
|
return response.decisionDisclosures?.map(({ decisionId }) => `[primitive] hidden Decision: prim decisions show ${decisionId}`).join("\n") ?? "";
|
|
40107
41497
|
}
|
|
40108
|
-
async function requestPreflight(
|
|
40109
|
-
const response = await getClient().post("/api/cli/decisions/conflict-check",
|
|
41498
|
+
async function requestPreflight(request3, signal = AbortSignal.timeout(PREFLIGHT_TIMEOUT_MS)) {
|
|
41499
|
+
const response = await getClient().post("/api/cli/decisions/conflict-check", request3, {
|
|
40110
41500
|
signal,
|
|
40111
41501
|
quietRefresh: true
|
|
40112
41502
|
});
|
|
@@ -40124,6 +41514,13 @@ function proposedChangeExcerpt(proposal) {
|
|
|
40124
41514
|
}
|
|
40125
41515
|
return boundedHealthError(proposal);
|
|
40126
41516
|
}
|
|
41517
|
+
var COVERAGE_NOTE = "[primitive] Decision coverage is incomplete; some candidates or evidence were not evaluated.";
|
|
41518
|
+
function coverageNote(response) {
|
|
41519
|
+
const coverage = response.evaluationCoverage;
|
|
41520
|
+
if (!coverage) return "";
|
|
41521
|
+
const settled = coverage.status === "completed" || isEmptyCheck(response);
|
|
41522
|
+
return !settled || coverage.selectionOmissions?.length || coverage.evidenceOmissions?.length ? COVERAGE_NOTE : "";
|
|
41523
|
+
}
|
|
40127
41524
|
function resultForPreflight(response, preview = "Review the requested change.", invocation, proposalTruncated = false) {
|
|
40128
41525
|
const verdict = response.verdict === "block" ? "deny" : response.verdict;
|
|
40129
41526
|
const silentCoverageOutcome = response.reasonCode === "coverage_unverified" || response.reasonCode === "candidate_set_truncated";
|
|
@@ -40159,6 +41556,7 @@ function resultForPreflight(response, preview = "Review the requested change.",
|
|
|
40159
41556
|
conflicts: response.conflicts,
|
|
40160
41557
|
message,
|
|
40161
41558
|
reasonCode: response.reasonCode,
|
|
41559
|
+
verdict: response.verdict,
|
|
40162
41560
|
evaluationCoverage: response.evaluationCoverage
|
|
40163
41561
|
},
|
|
40164
41562
|
preview
|
|
@@ -40190,7 +41588,7 @@ function unverifiedResult(message) {
|
|
|
40190
41588
|
}
|
|
40191
41589
|
|
|
40192
41590
|
// src/hooks/preflight-v4.ts
|
|
40193
|
-
import { createHash as
|
|
41591
|
+
import { createHash as createHash11 } from "crypto";
|
|
40194
41592
|
import { setTimeout as delay } from "timers/promises";
|
|
40195
41593
|
var PREFLIGHT_PROTOCOL_VERSION2 = 4;
|
|
40196
41594
|
var PREFLIGHT_WAIT_MS = 24e4;
|
|
@@ -40213,7 +41611,7 @@ function toolInputDigest(toolName, input) {
|
|
|
40213
41611
|
}
|
|
40214
41612
|
throw new Error("Tool input has no stable JSON identity");
|
|
40215
41613
|
}
|
|
40216
|
-
return
|
|
41614
|
+
return createHash11("sha256").update(canonical({ toolName, input: input ?? null })).digest("hex");
|
|
40217
41615
|
}
|
|
40218
41616
|
function isUnidentifiedPause(response) {
|
|
40219
41617
|
return response.state === "paused" && (response.verdict === "block" || response.verdict === "unavailable") && response.checkId === void 0 && response.evaluationId === void 0;
|
|
@@ -40525,7 +41923,7 @@ async function main() {
|
|
|
40525
41923
|
const callId = invocationId(envelope);
|
|
40526
41924
|
if (!binding || typeof sessionId !== "string" || !sessionId || !callId) {
|
|
40527
41925
|
await unverified(
|
|
40528
|
-
!binding ? "GitHub repo connection is required" : "Session or tool identity is missing"
|
|
41926
|
+
!binding ? cloudSetupPointer("GitHub repo connection is required") : "Session or tool identity is missing"
|
|
40529
41927
|
);
|
|
40530
41928
|
return;
|
|
40531
41929
|
}
|
|
@@ -40556,12 +41954,12 @@ async function main() {
|
|
|
40556
41954
|
proposal: collectScopeAdmits2 ? proposalFor(proposalInput) : ""
|
|
40557
41955
|
};
|
|
40558
41956
|
if (agent === "claude_code") {
|
|
40559
|
-
const
|
|
41957
|
+
const request4 = { ...common, protocolVersion: 3 };
|
|
40560
41958
|
let result2;
|
|
40561
41959
|
try {
|
|
40562
41960
|
const remaining = Math.floor(Math.min(PREFLIGHT_TIMEOUT_MS, deadline - performance.now()));
|
|
40563
41961
|
if (remaining <= 0) throw new Error("Deadline exceeded");
|
|
40564
|
-
const response = await requestPreflight(
|
|
41962
|
+
const response = await requestPreflight(request4, AbortSignal.timeout(remaining));
|
|
40565
41963
|
if (!response) {
|
|
40566
41964
|
await unverified("Decision check returned an invalid response");
|
|
40567
41965
|
return;
|
|
@@ -40569,21 +41967,18 @@ async function main() {
|
|
|
40569
41967
|
result2 = resultForPreflight(
|
|
40570
41968
|
response,
|
|
40571
41969
|
editPreview(toolName, envelope.tool_input, targets.paths),
|
|
40572
|
-
|
|
41970
|
+
request4,
|
|
40573
41971
|
collectScopeAdmits2 && protectedShell && proposalIsTruncated(proposalInput)
|
|
40574
41972
|
);
|
|
40575
41973
|
if (result2.verdict === "unavailable") {
|
|
40576
41974
|
result2.unavailable = `${result2.unavailable || "Decision check is unavailable"}; change was not verified.`;
|
|
40577
41975
|
}
|
|
40578
|
-
const coverage = response.evaluationCoverage;
|
|
40579
41976
|
const notes = [
|
|
40580
41977
|
...targets.coverage === "unverified" ? [
|
|
40581
41978
|
"[primitive] Some mutation targets could not be resolved; the complete change was not verified."
|
|
40582
41979
|
] : [],
|
|
40583
|
-
|
|
40584
|
-
|
|
40585
|
-
] : []
|
|
40586
|
-
];
|
|
41980
|
+
coverageNote(response)
|
|
41981
|
+
].filter(Boolean);
|
|
40587
41982
|
if (notes.length > 0) {
|
|
40588
41983
|
const note = notes.join("\n");
|
|
40589
41984
|
result2.reason = [result2.reason, note].filter(Boolean).join("\n");
|
|
@@ -40602,7 +41997,7 @@ async function main() {
|
|
|
40602
41997
|
);
|
|
40603
41998
|
return;
|
|
40604
41999
|
}
|
|
40605
|
-
const
|
|
42000
|
+
const request3 = {
|
|
40606
42001
|
...common,
|
|
40607
42002
|
protocolVersion: PREFLIGHT_PROTOCOL_VERSION2,
|
|
40608
42003
|
operation: "start",
|
|
@@ -40615,7 +42010,7 @@ async function main() {
|
|
|
40615
42010
|
};
|
|
40616
42011
|
let result;
|
|
40617
42012
|
try {
|
|
40618
|
-
const response = await waitForPreflight(
|
|
42013
|
+
const response = await waitForPreflight(request3, {
|
|
40619
42014
|
deadline,
|
|
40620
42015
|
stopOnConflict: true
|
|
40621
42016
|
});
|
|
@@ -40626,7 +42021,7 @@ async function main() {
|
|
|
40626
42021
|
result = resultForPreflight2(
|
|
40627
42022
|
response,
|
|
40628
42023
|
editPreview(toolName, envelope.tool_input, targets.paths),
|
|
40629
|
-
|
|
42024
|
+
request3,
|
|
40630
42025
|
collectScopeAdmits2 && (toolName === "Bash" || toolName === "Shell") && proposalIsTruncated(proposalInput)
|
|
40631
42026
|
);
|
|
40632
42027
|
} catch {
|