@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.129
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 +76 -5
- package/dist/{chunk-HZI5PBN4.js → chunk-BVGASV3B.js} +2047 -138
- package/dist/{chunk-72NIZMZN.js → chunk-DYXCJ6WZ.js} +15 -10
- package/dist/{chunk-TNWI3JWK.js → chunk-FHDTJP2C.js} +4 -2
- package/dist/{chunk-C4QNBSWB.js → chunk-HDL3UXYJ.js} +8 -8
- package/dist/{chunk-RV3JFSMX.js → chunk-IJ3W2YBM.js} +4 -4
- package/dist/{chunk-O65UVJZH.js → chunk-IZAEAALI.js} +2 -2
- package/dist/{chunk-H74RDXKP.js → chunk-KZNOT2YH.js} +2 -2
- package/dist/{chunk-R4EYLEIK.js → chunk-L7U3G4XR.js} +2 -2
- package/dist/{chunk-MGKSZSTV.js → chunk-LBZJD2I4.js} +3 -5
- package/dist/{chunk-UUQT5GMO.js → chunk-MMMY57UA.js} +22 -837
- package/dist/{chunk-H6X52UVF.js → chunk-NWWTFQP2.js} +1 -1
- package/dist/{chunk-WGTUNUIS.js → chunk-QSDWWEHF.js} +5 -5
- package/dist/{chunk-NVDPKW7Z.js → chunk-RAEOSDQ6.js} +3 -51
- package/dist/{chunk-KFRGVHGB.js → chunk-RS5ADTDF.js} +6 -6
- package/dist/{chunk-A5VTE43F.js → chunk-RWJ7WHTJ.js} +2 -2
- package/dist/{chunk-VVFVENU4.js → chunk-SJE7OWVS.js} +6 -6
- package/dist/{chunk-L6IL4N6Y.js → chunk-USJ4JGDC.js} +34 -34
- package/dist/{chunk-JCKOW45X.js → chunk-YPHDV5AS.js} +2 -2
- package/dist/{chunk-F3FDVHR7.js → chunk-YSV43WLK.js} +1 -1
- package/dist/{chunk-URYZDQFH.js → chunk-ZKIBD5MO.js} +3 -5
- package/dist/daemon/server.js +1769 -487
- package/dist/hook-runtime/daemon/server.js +1769 -487
- package/dist/hook-runtime/hooks/post-commit.js +611 -337
- package/dist/hook-runtime/hooks/post-rewrite.js +606 -332
- package/dist/hook-runtime/hooks/post-tool-use.js +1841 -683
- package/dist/hook-runtime/hooks/pre-commit.js +1713 -434
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1308 -150
- package/dist/hook-runtime/hooks/prim-hook.js +1863 -705
- package/dist/hook-runtime/hooks/session-end.js +538 -385
- package/dist/hook-runtime/hooks/session-start.js +1379 -233
- package/dist/hook-runtime/index.js +5438 -4052
- package/dist/hook-runtime/statusline-main.js +547 -273
- 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 +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +64 -22
- package/dist/index.js +396 -52
- package/dist/statusline-main.js +547 -273
- package/package.json +1 -1
|
@@ -63,6 +63,45 @@ import { existsSync as existsSync7 } from "fs";
|
|
|
63
63
|
import { existsSync, readFileSync } from "fs";
|
|
64
64
|
import { dirname, isAbsolute, join } from "path";
|
|
65
65
|
import { fileURLToPath } from "url";
|
|
66
|
+
|
|
67
|
+
// src/lib/semver.ts
|
|
68
|
+
function parseSemver(value) {
|
|
69
|
+
if (typeof value !== "string" || value.length > 256) return;
|
|
70
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
|
|
71
|
+
value
|
|
72
|
+
);
|
|
73
|
+
if (!match) return;
|
|
74
|
+
const prerelease = match[4]?.split(".") ?? [];
|
|
75
|
+
if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
79
|
+
}
|
|
80
|
+
function compareSemver(left, right) {
|
|
81
|
+
const a = parseSemver(left);
|
|
82
|
+
const b = parseSemver(right);
|
|
83
|
+
if (!a || !b) return;
|
|
84
|
+
for (let i = 0; i < a.core.length; i += 1) {
|
|
85
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
86
|
+
}
|
|
87
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
88
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
89
|
+
}
|
|
90
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
91
|
+
const x = a.prerelease[i];
|
|
92
|
+
const y = b.prerelease[i];
|
|
93
|
+
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
94
|
+
if (x === y) continue;
|
|
95
|
+
const xNumeric = /^\d+$/u.test(x);
|
|
96
|
+
const yNumeric = /^\d+$/u.test(y);
|
|
97
|
+
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
98
|
+
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
99
|
+
return x < y ? -1 : 1;
|
|
100
|
+
}
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/lib/bin-path.ts
|
|
66
105
|
var PKG_NAME = "@primitive.ai/prim";
|
|
67
106
|
var ROOT_WALK_LIMIT = 6;
|
|
68
107
|
var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
|
|
@@ -413,6 +452,7 @@ async function withFileLock(lockDir, operation, options = {}) {
|
|
|
413
452
|
}
|
|
414
453
|
|
|
415
454
|
// src/lib/git-hook-contract.ts
|
|
455
|
+
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
416
456
|
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
417
457
|
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
418
458
|
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
@@ -463,6 +503,7 @@ import { createRequire } from "module";
|
|
|
463
503
|
import { dirname as dirname4, join as join3 } from "path";
|
|
464
504
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
465
505
|
var require2 = createRequire(import.meta.url);
|
|
506
|
+
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
466
507
|
|
|
467
508
|
// src/lib/paths.ts
|
|
468
509
|
import { homedir } from "os";
|
|
@@ -493,7 +534,9 @@ function primConfigDirectory(options = {}) {
|
|
|
493
534
|
}
|
|
494
535
|
|
|
495
536
|
// src/lib/hook-runtime.ts
|
|
537
|
+
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
496
538
|
var RELEASE_PREFIX = "release-";
|
|
539
|
+
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
497
540
|
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
498
541
|
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
499
542
|
var HOOK_RUNTIME_ENTRIES = {
|
|
@@ -518,6 +561,171 @@ var SOURCE_ENTRIES = Object.fromEntries(
|
|
|
518
561
|
target.replace(/^dist\//u, "")
|
|
519
562
|
])
|
|
520
563
|
);
|
|
564
|
+
function hookRuntimePaths(options = {}) {
|
|
565
|
+
const env = options.env ?? process.env;
|
|
566
|
+
const configDir = primConfigDirectory({
|
|
567
|
+
...options,
|
|
568
|
+
env,
|
|
569
|
+
homeDir: options.homeDir ?? env.HOME ?? ""
|
|
570
|
+
});
|
|
571
|
+
const runtimeDir = join5(configDir, "hook-runtime");
|
|
572
|
+
return {
|
|
573
|
+
configDir,
|
|
574
|
+
launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
575
|
+
gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
576
|
+
runtimeDir,
|
|
577
|
+
releasesDir: join5(runtimeDir, "releases"),
|
|
578
|
+
current: join5(runtimeDir, "current"),
|
|
579
|
+
selectionLock: join5(runtimeDir, "selection.lock")
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
function sha256(path) {
|
|
583
|
+
return createHash("sha256").update(readFileSync3(path)).digest("hex");
|
|
584
|
+
}
|
|
585
|
+
function exactManifest(manifest) {
|
|
586
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
587
|
+
`;
|
|
588
|
+
}
|
|
589
|
+
function exactKeys(value, expected) {
|
|
590
|
+
const actual = Object.keys(value).sort();
|
|
591
|
+
const wanted = [...expected].sort();
|
|
592
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
593
|
+
}
|
|
594
|
+
function releaseId(manifest) {
|
|
595
|
+
return createHash("sha256").update(exactManifest(manifest)).digest("hex");
|
|
596
|
+
}
|
|
597
|
+
function runtimePackageJson(manifest) {
|
|
598
|
+
return `${JSON.stringify(
|
|
599
|
+
{
|
|
600
|
+
name: "@primitive.ai/prim",
|
|
601
|
+
version: manifest.version,
|
|
602
|
+
type: "module",
|
|
603
|
+
bin: HOOK_RUNTIME_ENTRIES
|
|
604
|
+
},
|
|
605
|
+
null,
|
|
606
|
+
2
|
|
607
|
+
)}
|
|
608
|
+
`;
|
|
609
|
+
}
|
|
610
|
+
function validateRelease(releaseDir, manifest) {
|
|
611
|
+
try {
|
|
612
|
+
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
613
|
+
if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
614
|
+
return false;
|
|
615
|
+
}
|
|
616
|
+
if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
617
|
+
return false;
|
|
618
|
+
}
|
|
619
|
+
if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
620
|
+
`) {
|
|
621
|
+
return false;
|
|
622
|
+
}
|
|
623
|
+
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
624
|
+
const target = join5(releaseDir, relativePath);
|
|
625
|
+
if (sha256(target) !== manifest.files[bin]) return false;
|
|
626
|
+
}
|
|
627
|
+
for (const [path, digest] of Object.entries(manifest.native ?? {})) {
|
|
628
|
+
if (sha256(join5(releaseDir, path)) !== digest) return false;
|
|
629
|
+
}
|
|
630
|
+
return true;
|
|
631
|
+
} catch {
|
|
632
|
+
return false;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
function directReleaseLayout(releaseDir, manifest) {
|
|
636
|
+
try {
|
|
637
|
+
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
638
|
+
for (const relativePath of [
|
|
639
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
640
|
+
...Object.keys(manifest.native ?? {})
|
|
641
|
+
]) {
|
|
642
|
+
for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
|
|
643
|
+
directories.add(join5(releaseDir, directory));
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
|
|
647
|
+
const files = [
|
|
648
|
+
"manifest.json",
|
|
649
|
+
"package.json",
|
|
650
|
+
"node",
|
|
651
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
652
|
+
...Object.keys(manifest.native ?? {})
|
|
653
|
+
];
|
|
654
|
+
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
|
|
655
|
+
if (![...directories].every(
|
|
656
|
+
(directory) => readdirSync(directory).every((name2) => owned.has(join5(directory, name2)))
|
|
657
|
+
))
|
|
658
|
+
return false;
|
|
659
|
+
return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
|
|
660
|
+
} catch {
|
|
661
|
+
return false;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
function readReleaseManifest(releaseDir, releaseName) {
|
|
665
|
+
try {
|
|
666
|
+
const manifestPath = join5(releaseDir, "manifest.json");
|
|
667
|
+
const manifestStat = statSync2(manifestPath);
|
|
668
|
+
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
669
|
+
const raw = readFileSync3(manifestPath, "utf8");
|
|
670
|
+
const parsed = JSON.parse(raw);
|
|
671
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
672
|
+
if (!exactKeys(parsed, [
|
|
673
|
+
"schemaVersion",
|
|
674
|
+
"version",
|
|
675
|
+
"nodePath",
|
|
676
|
+
"files",
|
|
677
|
+
..."native" in parsed ? ["native"] : []
|
|
678
|
+
]))
|
|
679
|
+
return null;
|
|
680
|
+
const candidate = parsed;
|
|
681
|
+
if (candidate.schemaVersion !== HOOK_RUNTIME_SCHEMA_VERSION || typeof candidate.version !== "string" || compareSemver(candidate.version, candidate.version) !== 0 || typeof candidate.nodePath !== "string" || !isAbsolute3(candidate.nodePath) || /[\r\n]/u.test(candidate.nodePath) || !candidate.files || typeof candidate.files !== "object" || Array.isArray(candidate.files) || !exactKeys(candidate.files, Object.keys(HOOK_RUNTIME_ENTRIES)) || Object.values(candidate.files).some(
|
|
682
|
+
(digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
|
|
683
|
+
)) {
|
|
684
|
+
return null;
|
|
685
|
+
}
|
|
686
|
+
if (candidate.native !== void 0 && (!candidate.native || typeof candidate.native !== "object" || Array.isArray(candidate.native) || !exactKeys(candidate.native, KEYRING_NATIVE_FILES) || Object.values(candidate.native).some(
|
|
687
|
+
(digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
|
|
688
|
+
)))
|
|
689
|
+
return null;
|
|
690
|
+
const manifest = candidate;
|
|
691
|
+
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
692
|
+
return null;
|
|
693
|
+
}
|
|
694
|
+
return manifest;
|
|
695
|
+
} catch {
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
function readSelectedRelease(paths) {
|
|
700
|
+
let raw;
|
|
701
|
+
try {
|
|
702
|
+
raw = readFileSync3(paths.current, "utf8");
|
|
703
|
+
} catch (error) {
|
|
704
|
+
if (error.code === "ENOENT") return null;
|
|
705
|
+
throw error;
|
|
706
|
+
}
|
|
707
|
+
const name2 = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
708
|
+
if (`${name2}
|
|
709
|
+
` !== raw || !RELEASE_NAME_RE.test(name2)) {
|
|
710
|
+
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
711
|
+
}
|
|
712
|
+
const dir = join5(paths.releasesDir, name2);
|
|
713
|
+
const manifest = readReleaseManifest(dir, name2);
|
|
714
|
+
if (!manifest) {
|
|
715
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
716
|
+
}
|
|
717
|
+
return { name: name2, dir, manifest };
|
|
718
|
+
}
|
|
719
|
+
function selectedHookRuntimeKeyringLoader(options = {}) {
|
|
720
|
+
try {
|
|
721
|
+
const selected = readSelectedRelease(hookRuntimePaths(options));
|
|
722
|
+
if (!selected?.manifest.native) return void 0;
|
|
723
|
+
const loader = join5(selected.dir, "native", "keyring.cjs");
|
|
724
|
+
return existsSync4(loader) ? loader : void 0;
|
|
725
|
+
} catch {
|
|
726
|
+
return void 0;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
521
729
|
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
522
730
|
set -eu
|
|
523
731
|
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
@@ -27417,6 +27625,8 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
27417
27625
|
}
|
|
27418
27626
|
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
27627
|
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';
|
|
27628
|
+
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}.`;
|
|
27629
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
27420
27630
|
function cloudSetupPointer(message, env = process.env) {
|
|
27421
27631
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
27422
27632
|
}
|
|
@@ -27435,13 +27645,20 @@ var GIT_TIMEOUT_MS = 1e3;
|
|
|
27435
27645
|
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
27436
27646
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
27437
27647
|
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
27648
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
27649
|
+
function gitChildEnvironment(env = process.env) {
|
|
27650
|
+
return Object.fromEntries(
|
|
27651
|
+
Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
|
|
27652
|
+
);
|
|
27653
|
+
}
|
|
27438
27654
|
function gitToplevel(cwd) {
|
|
27439
27655
|
try {
|
|
27440
27656
|
return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
|
|
27441
27657
|
cwd,
|
|
27442
27658
|
encoding: "utf-8",
|
|
27443
27659
|
stdio: ["ignore", "pipe", "ignore"],
|
|
27444
|
-
timeout: GIT_TIMEOUT_MS
|
|
27660
|
+
timeout: GIT_TIMEOUT_MS,
|
|
27661
|
+
env: gitChildEnvironment()
|
|
27445
27662
|
}).trim();
|
|
27446
27663
|
} catch {
|
|
27447
27664
|
return null;
|
|
@@ -27453,7 +27670,8 @@ function gitValue(cwd, args) {
|
|
|
27453
27670
|
cwd,
|
|
27454
27671
|
encoding: "utf-8",
|
|
27455
27672
|
stdio: ["ignore", "pipe", "ignore"],
|
|
27456
|
-
timeout: GIT_TIMEOUT_MS
|
|
27673
|
+
timeout: GIT_TIMEOUT_MS,
|
|
27674
|
+
env: gitChildEnvironment()
|
|
27457
27675
|
}).trim();
|
|
27458
27676
|
return value || void 0;
|
|
27459
27677
|
} catch {
|
|
@@ -27786,18 +28004,18 @@ function publicDecisionResponse(value) {
|
|
|
27786
28004
|
}
|
|
27787
28005
|
|
|
27788
28006
|
// src/client.ts
|
|
27789
|
-
import { createHash as
|
|
27790
|
-
import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as
|
|
28007
|
+
import { createHash as createHash9 } from "crypto";
|
|
28008
|
+
import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync9 } from "fs";
|
|
27791
28009
|
import { dirname as dirname8 } from "path";
|
|
27792
28010
|
|
|
27793
28011
|
// src/lib/credentials.ts
|
|
27794
|
-
import { createHash as
|
|
28012
|
+
import { createHash as createHash8 } from "crypto";
|
|
27795
28013
|
import { readFileSync as readFileSync11 } from "fs";
|
|
27796
|
-
import { join as
|
|
28014
|
+
import { join as join15 } from "path";
|
|
27797
28015
|
|
|
27798
28016
|
// src/lib/machine-credentials.ts
|
|
27799
28017
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
27800
|
-
import { createHash as
|
|
28018
|
+
import { createHash as createHash7, randomBytes as randomBytes4, randomUUID as randomUUID3 } from "crypto";
|
|
27801
28019
|
import {
|
|
27802
28020
|
chmodSync as chmodSync2,
|
|
27803
28021
|
existsSync as existsSync10,
|
|
@@ -27805,11 +28023,11 @@ import {
|
|
|
27805
28023
|
lstatSync as lstatSync6,
|
|
27806
28024
|
mkdirSync as mkdirSync5,
|
|
27807
28025
|
readFileSync as readFileSync10,
|
|
27808
|
-
rmSync as
|
|
28026
|
+
rmSync as rmSync8,
|
|
27809
28027
|
writeFileSync as writeFileSync5
|
|
27810
28028
|
} from "fs";
|
|
27811
28029
|
import { createRequire as createRequire2 } from "module";
|
|
27812
|
-
import { dirname as dirname7, join as
|
|
28030
|
+
import { dirname as dirname7, join as join14 } from "path";
|
|
27813
28031
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
27814
28032
|
|
|
27815
28033
|
// src/lib/machine-broker.ts
|
|
@@ -27986,10 +28204,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
27986
28204
|
"access_token",
|
|
27987
28205
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
27988
28206
|
);
|
|
27989
|
-
const
|
|
28207
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
27990
28208
|
return {
|
|
27991
28209
|
accessToken,
|
|
27992
|
-
refreshToken:
|
|
28210
|
+
refreshToken: refreshToken3,
|
|
27993
28211
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
27994
28212
|
};
|
|
27995
28213
|
}
|
|
@@ -28564,32 +28782,995 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
28564
28782
|
}
|
|
28565
28783
|
}
|
|
28566
28784
|
|
|
28785
|
+
// src/lib/session-identity.ts
|
|
28786
|
+
import { execFile } from "child_process";
|
|
28787
|
+
import { createHash as createHash6 } from "crypto";
|
|
28788
|
+
import { rmSync as rmSync7 } from "fs";
|
|
28789
|
+
import { join as join13 } from "path";
|
|
28790
|
+
import { promisify } from "util";
|
|
28791
|
+
|
|
28792
|
+
// src/lib/terminal-safe.ts
|
|
28793
|
+
function replaceIsolatedSurrogates(value) {
|
|
28794
|
+
let out = "";
|
|
28795
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
28796
|
+
const unit = value.charCodeAt(index);
|
|
28797
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
28798
|
+
const next = value.charCodeAt(index + 1);
|
|
28799
|
+
if (next >= 56320 && next <= 57343) {
|
|
28800
|
+
out += value[index] + value[index + 1];
|
|
28801
|
+
index += 1;
|
|
28802
|
+
} else {
|
|
28803
|
+
out += "\uFFFD";
|
|
28804
|
+
}
|
|
28805
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
28806
|
+
out += "\uFFFD";
|
|
28807
|
+
} else {
|
|
28808
|
+
out += value[index];
|
|
28809
|
+
}
|
|
28810
|
+
}
|
|
28811
|
+
return out;
|
|
28812
|
+
}
|
|
28813
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
28814
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
28815
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
28816
|
+
point === 1564 || // Arabic letter mark
|
|
28817
|
+
point === 6158 || // Mongolian vowel separator
|
|
28818
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
28819
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
28820
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
28821
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
28822
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
28823
|
+
point >= 917504 && point <= 917631;
|
|
28824
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
28825
|
+
}
|
|
28826
|
+
function terminalSafeText(value) {
|
|
28827
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
28828
|
+
}
|
|
28829
|
+
function terminalSafeLine(value) {
|
|
28830
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
28831
|
+
}
|
|
28832
|
+
|
|
28833
|
+
// src/lib/session-identity.ts
|
|
28834
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
28835
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
28836
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
28837
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
28838
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
28839
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
28840
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
28841
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
28842
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
28843
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
28844
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
28845
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
28846
|
+
token: "/api/cli/session-identity/token",
|
|
28847
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
28848
|
+
link: "/api/cli/session-identity/link"
|
|
28849
|
+
};
|
|
28850
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
28851
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
28852
|
+
var GIT_TIMEOUT_MS3 = 1e4;
|
|
28853
|
+
var POLL_BUDGET_MS = 15e3;
|
|
28854
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
28855
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
28856
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
28857
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
28858
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
28859
|
+
function sessionIdentityRequested(env = process.env) {
|
|
28860
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
28861
|
+
}
|
|
28862
|
+
function sessionIdentityMode(deps = {}) {
|
|
28863
|
+
const env = deps.env ?? process.env;
|
|
28864
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
28865
|
+
}
|
|
28866
|
+
function failure(code, cause, remedy) {
|
|
28867
|
+
return { status: "failed", code, cause, remedy };
|
|
28868
|
+
}
|
|
28869
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
28870
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
28871
|
+
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';
|
|
28872
|
+
var SESSION_REVOKED = failure(
|
|
28873
|
+
"session_revoked",
|
|
28874
|
+
"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",
|
|
28875
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
28876
|
+
);
|
|
28877
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
28878
|
+
"challenge_expired",
|
|
28879
|
+
"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)",
|
|
28880
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
28881
|
+
);
|
|
28882
|
+
var CHALLENGE_GONE = failure(
|
|
28883
|
+
"challenge_not_found",
|
|
28884
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
28885
|
+
NEW_SESSION_REMEDY
|
|
28886
|
+
);
|
|
28887
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
28888
|
+
function rejectionFailure(reason, repository) {
|
|
28889
|
+
switch (reason) {
|
|
28890
|
+
case "identity_mismatch":
|
|
28891
|
+
return failure(
|
|
28892
|
+
"identity_mismatch",
|
|
28893
|
+
"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",
|
|
28894
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
28895
|
+
);
|
|
28896
|
+
case "push_after_expiry":
|
|
28897
|
+
return failure(
|
|
28898
|
+
"push_after_expiry",
|
|
28899
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
28900
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
28901
|
+
);
|
|
28902
|
+
case "repository_mismatch":
|
|
28903
|
+
return failure(
|
|
28904
|
+
"repository_mismatch",
|
|
28905
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
28906
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
28907
|
+
);
|
|
28908
|
+
case "conflicting_push":
|
|
28909
|
+
return failure(
|
|
28910
|
+
"conflicting_push",
|
|
28911
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
28912
|
+
NEW_SESSION_REMEDY
|
|
28913
|
+
);
|
|
28914
|
+
case "unsupported_sender":
|
|
28915
|
+
return failure(
|
|
28916
|
+
"unsupported_sender",
|
|
28917
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
28918
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
28919
|
+
);
|
|
28920
|
+
default:
|
|
28921
|
+
return failure(
|
|
28922
|
+
"challenge_rejected",
|
|
28923
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
28924
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
28925
|
+
);
|
|
28926
|
+
}
|
|
28927
|
+
}
|
|
28928
|
+
function sessionIdentityMessage(outcome) {
|
|
28929
|
+
if (outcome.status === "link_required")
|
|
28930
|
+
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.`;
|
|
28931
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
28932
|
+
}
|
|
28933
|
+
function hash(value) {
|
|
28934
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
28935
|
+
}
|
|
28936
|
+
function sessionContext(deps) {
|
|
28937
|
+
const env = deps.env ?? process.env;
|
|
28938
|
+
const environment = environmentCredentials(deps);
|
|
28939
|
+
if (!environment)
|
|
28940
|
+
return failure(
|
|
28941
|
+
"environment_credential_missing",
|
|
28942
|
+
"the cloud environment has no environment credential",
|
|
28943
|
+
'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'
|
|
28944
|
+
);
|
|
28945
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
28946
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
28947
|
+
return failure(
|
|
28948
|
+
"session_id_missing",
|
|
28949
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
28950
|
+
NEW_SESSION_REMEDY
|
|
28951
|
+
);
|
|
28952
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
28953
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
28954
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
28955
|
+
return {
|
|
28956
|
+
directory,
|
|
28957
|
+
apiUrl,
|
|
28958
|
+
clientId: environment.clientId,
|
|
28959
|
+
generation: environment.generation,
|
|
28960
|
+
sessionId,
|
|
28961
|
+
tokenPath: join13(directory, `session_identity_${key}.json`),
|
|
28962
|
+
statePath: join13(directory, `session_identity_${key}.state.json`),
|
|
28963
|
+
lockPath: join13(directory, "session-identity.lock")
|
|
28964
|
+
};
|
|
28965
|
+
}
|
|
28966
|
+
function readRecord(path) {
|
|
28967
|
+
try {
|
|
28968
|
+
const value = readMachineMetadata(path);
|
|
28969
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
28970
|
+
} catch {
|
|
28971
|
+
return void 0;
|
|
28972
|
+
}
|
|
28973
|
+
}
|
|
28974
|
+
function finiteNumber(value) {
|
|
28975
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
28976
|
+
}
|
|
28977
|
+
function readToken(context) {
|
|
28978
|
+
const data = readRecord(context.tokenPath);
|
|
28979
|
+
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))
|
|
28980
|
+
return void 0;
|
|
28981
|
+
const identity = data.identity;
|
|
28982
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
28983
|
+
return void 0;
|
|
28984
|
+
return data;
|
|
28985
|
+
}
|
|
28986
|
+
function readState(context) {
|
|
28987
|
+
const data = readRecord(context.statePath);
|
|
28988
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
28989
|
+
return void 0;
|
|
28990
|
+
return data;
|
|
28991
|
+
}
|
|
28992
|
+
function writeToken(context, record) {
|
|
28993
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
28994
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
28995
|
+
rmSync7(context.statePath, { force: true });
|
|
28996
|
+
}
|
|
28997
|
+
function writeState(context, state) {
|
|
28998
|
+
try {
|
|
28999
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
29000
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
29001
|
+
} catch {
|
|
29002
|
+
}
|
|
29003
|
+
}
|
|
29004
|
+
function tokenValid(record, now = Date.now()) {
|
|
29005
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
29006
|
+
}
|
|
29007
|
+
function tokenFresh(record, now = Date.now()) {
|
|
29008
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
29009
|
+
}
|
|
29010
|
+
function toCredential(record) {
|
|
29011
|
+
return {
|
|
29012
|
+
issuer: record.issuer,
|
|
29013
|
+
audience: record.audience,
|
|
29014
|
+
...record.identity,
|
|
29015
|
+
accessToken: record.accessToken,
|
|
29016
|
+
expiresAt: record.expiresAt,
|
|
29017
|
+
apiUrl: record.apiUrl,
|
|
29018
|
+
generation: record.generation,
|
|
29019
|
+
storage: "environment",
|
|
29020
|
+
session: {
|
|
29021
|
+
userId: record.userId,
|
|
29022
|
+
displayName: record.displayName,
|
|
29023
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
29024
|
+
refreshAfter: record.refreshAfter
|
|
29025
|
+
}
|
|
29026
|
+
};
|
|
29027
|
+
}
|
|
29028
|
+
function identified(record, reused) {
|
|
29029
|
+
return {
|
|
29030
|
+
status: "ok",
|
|
29031
|
+
credential: toCredential(record),
|
|
29032
|
+
displayName: record.displayName,
|
|
29033
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
29034
|
+
reused
|
|
29035
|
+
};
|
|
29036
|
+
}
|
|
29037
|
+
function cachedSessionCredential(deps = {}) {
|
|
29038
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
29039
|
+
let context;
|
|
29040
|
+
try {
|
|
29041
|
+
context = sessionContext(deps);
|
|
29042
|
+
} catch {
|
|
29043
|
+
return void 0;
|
|
29044
|
+
}
|
|
29045
|
+
if ("status" in context) return void 0;
|
|
29046
|
+
const record = readToken(context);
|
|
29047
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
29048
|
+
}
|
|
29049
|
+
function outcomeFromState(state) {
|
|
29050
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
29051
|
+
return {
|
|
29052
|
+
status: "link_required",
|
|
29053
|
+
githubLogin: state.githubLogin,
|
|
29054
|
+
challengeId: state.challengeId,
|
|
29055
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
29056
|
+
};
|
|
29057
|
+
return failure(
|
|
29058
|
+
state.code,
|
|
29059
|
+
state.cause ?? "the last identity check failed",
|
|
29060
|
+
state.remedy ?? RETRY_REMEDY
|
|
29061
|
+
);
|
|
29062
|
+
}
|
|
29063
|
+
function parseInstant(value) {
|
|
29064
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
29065
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
29066
|
+
const parsed = Date.parse(value);
|
|
29067
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
29068
|
+
}
|
|
29069
|
+
return void 0;
|
|
29070
|
+
}
|
|
29071
|
+
async function sendJson(url, init, fetchImpl) {
|
|
29072
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
29073
|
+
let value;
|
|
29074
|
+
try {
|
|
29075
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
29076
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
29077
|
+
} catch {
|
|
29078
|
+
value = void 0;
|
|
29079
|
+
}
|
|
29080
|
+
return { status: response.status, value };
|
|
29081
|
+
}
|
|
29082
|
+
function environmentOnly(deps) {
|
|
29083
|
+
return { ...deps, environmentOnly: true };
|
|
29084
|
+
}
|
|
29085
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
29086
|
+
const send = async (credential2) => {
|
|
29087
|
+
const headers = { "Content-Type": "application/json" };
|
|
29088
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
29089
|
+
if (credential2.tokenInjection) {
|
|
29090
|
+
const response = await forwardMachineRequest(
|
|
29091
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
29092
|
+
signal,
|
|
29093
|
+
environmentOnly(deps)
|
|
29094
|
+
);
|
|
29095
|
+
const parsed = await response.json().catch(() => void 0);
|
|
29096
|
+
return {
|
|
29097
|
+
status: response.status,
|
|
29098
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
29099
|
+
};
|
|
29100
|
+
}
|
|
29101
|
+
return sendJson(
|
|
29102
|
+
`${credential2.apiUrl}${path}`,
|
|
29103
|
+
{
|
|
29104
|
+
method,
|
|
29105
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
29106
|
+
...text === void 0 ? {} : { body: text },
|
|
29107
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS3)
|
|
29108
|
+
},
|
|
29109
|
+
deps.fetch ?? fetch
|
|
29110
|
+
);
|
|
29111
|
+
};
|
|
29112
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
29113
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
29114
|
+
let answer = await send(credential);
|
|
29115
|
+
if (answer.status === 401) {
|
|
29116
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
29117
|
+
if (!credential)
|
|
29118
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
29119
|
+
answer = await send(credential);
|
|
29120
|
+
}
|
|
29121
|
+
return answer;
|
|
29122
|
+
}
|
|
29123
|
+
function environmentFailure(error, apiUrl) {
|
|
29124
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
29125
|
+
return failure(
|
|
29126
|
+
"environment_credential_rejected",
|
|
29127
|
+
"Primitive rejected the cloud environment's credential",
|
|
29128
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
29129
|
+
);
|
|
29130
|
+
const host = (() => {
|
|
29131
|
+
try {
|
|
29132
|
+
return new URL(apiUrl).hostname;
|
|
29133
|
+
} catch {
|
|
29134
|
+
return "Primitive";
|
|
29135
|
+
}
|
|
29136
|
+
})();
|
|
29137
|
+
return failure(
|
|
29138
|
+
"identity_unavailable",
|
|
29139
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
29140
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
29141
|
+
);
|
|
29142
|
+
}
|
|
29143
|
+
function answerError(answer) {
|
|
29144
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
29145
|
+
}
|
|
29146
|
+
async function git(root, args, signal) {
|
|
29147
|
+
try {
|
|
29148
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
29149
|
+
cwd: root,
|
|
29150
|
+
encoding: "utf8",
|
|
29151
|
+
timeout: GIT_TIMEOUT_MS3,
|
|
29152
|
+
signal,
|
|
29153
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
29154
|
+
maxBuffer: 1024 * 1024
|
|
29155
|
+
});
|
|
29156
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
29157
|
+
} catch (error) {
|
|
29158
|
+
const failed = error;
|
|
29159
|
+
return {
|
|
29160
|
+
ok: false,
|
|
29161
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
29162
|
+
stdout: failed.stdout ?? "",
|
|
29163
|
+
stderr: failed.stderr ?? "",
|
|
29164
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
29165
|
+
};
|
|
29166
|
+
}
|
|
29167
|
+
}
|
|
29168
|
+
function gitDetail(stderr) {
|
|
29169
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
29170
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
29171
|
+
}
|
|
29172
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
29173
|
+
await new Promise((resolve7, reject) => {
|
|
29174
|
+
const timer = setTimeout(resolve7, milliseconds);
|
|
29175
|
+
signal?.addEventListener(
|
|
29176
|
+
"abort",
|
|
29177
|
+
() => {
|
|
29178
|
+
clearTimeout(timer);
|
|
29179
|
+
reject(signal.reason);
|
|
29180
|
+
},
|
|
29181
|
+
{ once: true }
|
|
29182
|
+
);
|
|
29183
|
+
});
|
|
29184
|
+
}
|
|
29185
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
29186
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
29187
|
+
const deadline2 = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
29188
|
+
let delay2 = POLL_FIRST_DELAY_MS;
|
|
29189
|
+
let unreachable;
|
|
29190
|
+
for (; ; ) {
|
|
29191
|
+
const remaining = deadline2 - Date.now();
|
|
29192
|
+
if (remaining <= 0) break;
|
|
29193
|
+
await sleep(Math.min(delay2, remaining), signal);
|
|
29194
|
+
delay2 = Math.min(POLL_MAX_DELAY_MS, Math.round(delay2 * 1.5));
|
|
29195
|
+
let answer;
|
|
29196
|
+
try {
|
|
29197
|
+
answer = await environmentRequest(
|
|
29198
|
+
"GET",
|
|
29199
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
29200
|
+
void 0,
|
|
29201
|
+
deps,
|
|
29202
|
+
signal
|
|
29203
|
+
);
|
|
29204
|
+
} catch (error) {
|
|
29205
|
+
signal?.throwIfAborted();
|
|
29206
|
+
unreachable = error;
|
|
29207
|
+
continue;
|
|
29208
|
+
}
|
|
29209
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
29210
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29211
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
29212
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
29213
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
29214
|
+
continue;
|
|
29215
|
+
}
|
|
29216
|
+
unreachable = void 0;
|
|
29217
|
+
const status = answer.value;
|
|
29218
|
+
if (status?.status === "verified")
|
|
29219
|
+
return {
|
|
29220
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
29221
|
+
};
|
|
29222
|
+
if (status?.status === "expired")
|
|
29223
|
+
return failure(
|
|
29224
|
+
"challenge_expired",
|
|
29225
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
29226
|
+
NEW_SESSION_REMEDY
|
|
29227
|
+
);
|
|
29228
|
+
if (status?.status === "rejected")
|
|
29229
|
+
return rejectionFailure(status.reason, repository);
|
|
29230
|
+
}
|
|
29231
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
29232
|
+
return failure(
|
|
29233
|
+
"webhook_timeout",
|
|
29234
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
29235
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
29236
|
+
);
|
|
29237
|
+
}
|
|
29238
|
+
function parseTokenAnswer(value) {
|
|
29239
|
+
if (!value) return void 0;
|
|
29240
|
+
const user = value.user;
|
|
29241
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
29242
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
29243
|
+
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))
|
|
29244
|
+
return void 0;
|
|
29245
|
+
return {
|
|
29246
|
+
accessToken: value.accessToken,
|
|
29247
|
+
expiresAt,
|
|
29248
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
29249
|
+
userId: user.id,
|
|
29250
|
+
displayName: user.displayName,
|
|
29251
|
+
organizationId: value.organizationId
|
|
29252
|
+
};
|
|
29253
|
+
}
|
|
29254
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
29255
|
+
"server_contract",
|
|
29256
|
+
"Primitive's answer did not identify the linked member",
|
|
29257
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
29258
|
+
);
|
|
29259
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
29260
|
+
let identity;
|
|
29261
|
+
let environment;
|
|
29262
|
+
try {
|
|
29263
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
29264
|
+
identity = await verifyMachineIdentity(
|
|
29265
|
+
context.apiUrl,
|
|
29266
|
+
answer.accessToken,
|
|
29267
|
+
context.clientId,
|
|
29268
|
+
signal,
|
|
29269
|
+
deps.fetch
|
|
29270
|
+
);
|
|
29271
|
+
} catch (error) {
|
|
29272
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
29273
|
+
return SERVER_CONTRACT_FAILURE;
|
|
29274
|
+
return environmentFailure(error, context.apiUrl);
|
|
29275
|
+
}
|
|
29276
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
29277
|
+
return SERVER_CONTRACT_FAILURE;
|
|
29278
|
+
return {
|
|
29279
|
+
version: 1,
|
|
29280
|
+
apiUrl: context.apiUrl,
|
|
29281
|
+
clientId: context.clientId,
|
|
29282
|
+
generation: context.generation,
|
|
29283
|
+
sessionId: context.sessionId,
|
|
29284
|
+
issuer: environment.issuer,
|
|
29285
|
+
audience: environment.audience,
|
|
29286
|
+
accessToken: answer.accessToken,
|
|
29287
|
+
expiresAt: answer.expiresAt,
|
|
29288
|
+
refreshAfter: answer.refreshAfter,
|
|
29289
|
+
userId: answer.userId,
|
|
29290
|
+
displayName: answer.displayName,
|
|
29291
|
+
organizationId: answer.organizationId,
|
|
29292
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
29293
|
+
identity,
|
|
29294
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
29295
|
+
};
|
|
29296
|
+
}
|
|
29297
|
+
async function refreshToken(context, record, deps, signal) {
|
|
29298
|
+
let answer;
|
|
29299
|
+
try {
|
|
29300
|
+
answer = await environmentRequest(
|
|
29301
|
+
"POST",
|
|
29302
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
29303
|
+
{ accessToken: record.accessToken },
|
|
29304
|
+
deps,
|
|
29305
|
+
signal
|
|
29306
|
+
);
|
|
29307
|
+
} catch (error) {
|
|
29308
|
+
signal?.throwIfAborted();
|
|
29309
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
29310
|
+
}
|
|
29311
|
+
const code = answerError(answer);
|
|
29312
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
29313
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
29314
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29315
|
+
return {
|
|
29316
|
+
status: "refused",
|
|
29317
|
+
failure: environmentFailure(
|
|
29318
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
29319
|
+
context.apiUrl
|
|
29320
|
+
)
|
|
29321
|
+
};
|
|
29322
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
29323
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
29324
|
+
return { status: "unavailable" };
|
|
29325
|
+
return {
|
|
29326
|
+
status: "ok",
|
|
29327
|
+
record: {
|
|
29328
|
+
...record,
|
|
29329
|
+
accessToken: token.accessToken,
|
|
29330
|
+
expiresAt: token.expiresAt,
|
|
29331
|
+
refreshAfter: token.refreshAfter,
|
|
29332
|
+
displayName: token.displayName
|
|
29333
|
+
}
|
|
29334
|
+
};
|
|
29335
|
+
}
|
|
29336
|
+
function exchangeRefusal(answer, repository) {
|
|
29337
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
29338
|
+
if (answer.status !== 409) return void 0;
|
|
29339
|
+
switch (answerError(answer)) {
|
|
29340
|
+
case "identity_mismatch":
|
|
29341
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
29342
|
+
case "challenge_rejected":
|
|
29343
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
29344
|
+
case "challenge_expired":
|
|
29345
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
29346
|
+
case "challenge_already_exchanged":
|
|
29347
|
+
return failure(
|
|
29348
|
+
"challenge_already_exchanged",
|
|
29349
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
29350
|
+
NEW_SESSION_REMEDY
|
|
29351
|
+
);
|
|
29352
|
+
case "challenge_pending":
|
|
29353
|
+
return failure(
|
|
29354
|
+
"webhook_timeout",
|
|
29355
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
29356
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
29357
|
+
);
|
|
29358
|
+
default:
|
|
29359
|
+
return void 0;
|
|
29360
|
+
}
|
|
29361
|
+
}
|
|
29362
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
29363
|
+
let answer;
|
|
29364
|
+
try {
|
|
29365
|
+
answer = await environmentRequest(
|
|
29366
|
+
"POST",
|
|
29367
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
29368
|
+
{ challengeId: challenge.challengeId },
|
|
29369
|
+
deps,
|
|
29370
|
+
signal
|
|
29371
|
+
);
|
|
29372
|
+
} catch (error) {
|
|
29373
|
+
signal?.throwIfAborted();
|
|
29374
|
+
return environmentFailure(error, context.apiUrl);
|
|
29375
|
+
}
|
|
29376
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
29377
|
+
const login = answer.value?.githubLogin;
|
|
29378
|
+
return {
|
|
29379
|
+
status: "link_required",
|
|
29380
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
29381
|
+
challengeId: challenge.challengeId,
|
|
29382
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
29383
|
+
};
|
|
29384
|
+
}
|
|
29385
|
+
const refused = exchangeRefusal(
|
|
29386
|
+
answer,
|
|
29387
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
29388
|
+
);
|
|
29389
|
+
if (refused) return refused;
|
|
29390
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
29391
|
+
if (!token) {
|
|
29392
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29393
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
29394
|
+
return answer.status >= 500 ? environmentFailure(
|
|
29395
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
29396
|
+
context.apiUrl
|
|
29397
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
29398
|
+
}
|
|
29399
|
+
return recordFor(
|
|
29400
|
+
context,
|
|
29401
|
+
token,
|
|
29402
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
29403
|
+
deps,
|
|
29404
|
+
signal
|
|
29405
|
+
);
|
|
29406
|
+
}
|
|
29407
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
29408
|
+
const env = deps.env ?? process.env;
|
|
29409
|
+
const repository = githubRepositoryFullName(root);
|
|
29410
|
+
if (!repository)
|
|
29411
|
+
return failure(
|
|
29412
|
+
"repository_unidentified",
|
|
29413
|
+
"this checkout does not name its GitHub repository",
|
|
29414
|
+
"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"
|
|
29415
|
+
);
|
|
29416
|
+
const branch = currentBranch(root);
|
|
29417
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
29418
|
+
return failure(
|
|
29419
|
+
"not_session_branch",
|
|
29420
|
+
`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`,
|
|
29421
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
29422
|
+
);
|
|
29423
|
+
attempt.branch = branch;
|
|
29424
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
29425
|
+
if (!baseSha) {
|
|
29426
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
29427
|
+
baseSha = head.stdout.trim();
|
|
29428
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
29429
|
+
return failure(
|
|
29430
|
+
"no_commit",
|
|
29431
|
+
"this checkout has no commit to create the session branch at",
|
|
29432
|
+
NEW_SESSION_REMEDY
|
|
29433
|
+
);
|
|
29434
|
+
}
|
|
29435
|
+
const published = await git(
|
|
29436
|
+
root,
|
|
29437
|
+
[
|
|
29438
|
+
"for-each-ref",
|
|
29439
|
+
"--count=1",
|
|
29440
|
+
"--format=%(refname)",
|
|
29441
|
+
"--contains",
|
|
29442
|
+
baseSha,
|
|
29443
|
+
"refs/remotes/origin/"
|
|
29444
|
+
],
|
|
29445
|
+
signal
|
|
29446
|
+
);
|
|
29447
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
29448
|
+
return failure(
|
|
29449
|
+
"unpublished_commits",
|
|
29450
|
+
`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`,
|
|
29451
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
29452
|
+
);
|
|
29453
|
+
attempt.baseSha = baseSha;
|
|
29454
|
+
const remote = await git(
|
|
29455
|
+
root,
|
|
29456
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
29457
|
+
signal
|
|
29458
|
+
);
|
|
29459
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
29460
|
+
if (remote.ok && recorded) {
|
|
29461
|
+
Object.assign(attempt, recorded);
|
|
29462
|
+
return { ...recorded, repository };
|
|
29463
|
+
}
|
|
29464
|
+
if (remote.ok)
|
|
29465
|
+
return failure(
|
|
29466
|
+
"branch_exists",
|
|
29467
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
29468
|
+
NEW_SESSION_REMEDY
|
|
29469
|
+
);
|
|
29470
|
+
if (remote.code !== 2)
|
|
29471
|
+
return failure(
|
|
29472
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
29473
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
29474
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
29475
|
+
);
|
|
29476
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
29477
|
+
Object.assign(attempt, recorded);
|
|
29478
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
29479
|
+
}
|
|
29480
|
+
let answer;
|
|
29481
|
+
try {
|
|
29482
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
29483
|
+
answer = await environmentRequest(
|
|
29484
|
+
"POST",
|
|
29485
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
29486
|
+
{
|
|
29487
|
+
repositoryFullName: repository,
|
|
29488
|
+
claudeSessionId: context.sessionId,
|
|
29489
|
+
branch,
|
|
29490
|
+
baseSha,
|
|
29491
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
29492
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
29493
|
+
},
|
|
29494
|
+
deps,
|
|
29495
|
+
signal
|
|
29496
|
+
);
|
|
29497
|
+
} catch (error) {
|
|
29498
|
+
signal?.throwIfAborted();
|
|
29499
|
+
return environmentFailure(error, context.apiUrl);
|
|
29500
|
+
}
|
|
29501
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
29502
|
+
return failure(
|
|
29503
|
+
"repository_not_connected",
|
|
29504
|
+
`${repository} is not connected to Primitive`,
|
|
29505
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
29506
|
+
);
|
|
29507
|
+
if (answer.status === 401 || answer.status === 403)
|
|
29508
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
29509
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
29510
|
+
return failure(
|
|
29511
|
+
"challenge_open",
|
|
29512
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
29513
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
29514
|
+
);
|
|
29515
|
+
if (answer.status === 429)
|
|
29516
|
+
return failure(
|
|
29517
|
+
"too_many_challenges",
|
|
29518
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
29519
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
29520
|
+
);
|
|
29521
|
+
const challengeId = answer.value?.challengeId;
|
|
29522
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
29523
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
29524
|
+
return answer.status >= 500 ? environmentFailure(
|
|
29525
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
29526
|
+
context.apiUrl
|
|
29527
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
29528
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
29529
|
+
attempt.challengeId = challengeId;
|
|
29530
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
29531
|
+
return pushSessionBranch(
|
|
29532
|
+
root,
|
|
29533
|
+
repository,
|
|
29534
|
+
branch,
|
|
29535
|
+
baseSha,
|
|
29536
|
+
{ challengeId, challengeExpiresAt },
|
|
29537
|
+
signal
|
|
29538
|
+
);
|
|
29539
|
+
}
|
|
29540
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
29541
|
+
const push = await git(
|
|
29542
|
+
root,
|
|
29543
|
+
[
|
|
29544
|
+
"-c",
|
|
29545
|
+
"core.hooksPath=/dev/null",
|
|
29546
|
+
"-c",
|
|
29547
|
+
"push.followTags=false",
|
|
29548
|
+
"-c",
|
|
29549
|
+
"push.recurseSubmodules=no",
|
|
29550
|
+
"-c",
|
|
29551
|
+
"push.gpgSign=false",
|
|
29552
|
+
"-c",
|
|
29553
|
+
"push.pushOption=",
|
|
29554
|
+
"push",
|
|
29555
|
+
"--no-verify",
|
|
29556
|
+
"--no-follow-tags",
|
|
29557
|
+
"--no-recurse-submodules",
|
|
29558
|
+
"--no-signed",
|
|
29559
|
+
"--quiet",
|
|
29560
|
+
"origin",
|
|
29561
|
+
`${baseSha}:refs/heads/${branch}`
|
|
29562
|
+
],
|
|
29563
|
+
signal
|
|
29564
|
+
);
|
|
29565
|
+
if (!push.ok)
|
|
29566
|
+
return push.timedOut ? failure(
|
|
29567
|
+
"push_timeout",
|
|
29568
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS3 / 1e3} s`,
|
|
29569
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
29570
|
+
) : failure(
|
|
29571
|
+
"push_refused",
|
|
29572
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
29573
|
+
`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}`
|
|
29574
|
+
);
|
|
29575
|
+
return { ...challenge, repository };
|
|
29576
|
+
}
|
|
29577
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
29578
|
+
let context;
|
|
29579
|
+
try {
|
|
29580
|
+
context = sessionContext(deps);
|
|
29581
|
+
} catch (error) {
|
|
29582
|
+
return failure(
|
|
29583
|
+
"environment_credential_invalid",
|
|
29584
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
29585
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
29586
|
+
);
|
|
29587
|
+
}
|
|
29588
|
+
if ("status" in context) return context;
|
|
29589
|
+
const ctx = context;
|
|
29590
|
+
const startedAt = Date.now();
|
|
29591
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
29592
|
+
return withFileLock(
|
|
29593
|
+
ctx.lockPath,
|
|
29594
|
+
async () => {
|
|
29595
|
+
const record = readToken(ctx);
|
|
29596
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
29597
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
29598
|
+
if (record) {
|
|
29599
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
29600
|
+
if (refreshed.status === "ok") {
|
|
29601
|
+
writeToken(ctx, refreshed.record);
|
|
29602
|
+
return identified(refreshed.record, true);
|
|
29603
|
+
}
|
|
29604
|
+
if (refreshed.status === "refused") {
|
|
29605
|
+
rmSync7(ctx.tokenPath, { force: true });
|
|
29606
|
+
writeState(ctx, {
|
|
29607
|
+
sessionId: ctx.sessionId,
|
|
29608
|
+
status: "failed",
|
|
29609
|
+
code: refreshed.failure.code,
|
|
29610
|
+
cause: refreshed.failure.cause,
|
|
29611
|
+
remedy: refreshed.failure.remedy,
|
|
29612
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
29613
|
+
at: Date.now()
|
|
29614
|
+
});
|
|
29615
|
+
return refreshed.failure;
|
|
29616
|
+
}
|
|
29617
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
29618
|
+
}
|
|
29619
|
+
const state = readState(ctx);
|
|
29620
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
29621
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
29622
|
+
if (!options.explicit) {
|
|
29623
|
+
if (!root || !(record || state))
|
|
29624
|
+
return failure(
|
|
29625
|
+
"not_identified",
|
|
29626
|
+
"this session has not identified who started it yet",
|
|
29627
|
+
RETRY_REMEDY
|
|
29628
|
+
);
|
|
29629
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
29630
|
+
} else if (state && state.at >= startedAt) {
|
|
29631
|
+
return outcomeFromState(state);
|
|
29632
|
+
}
|
|
29633
|
+
if (!root)
|
|
29634
|
+
return failure(
|
|
29635
|
+
"repository_missing",
|
|
29636
|
+
"this is not a git repository",
|
|
29637
|
+
"run it in the repository the session cloned"
|
|
29638
|
+
);
|
|
29639
|
+
const attempt = { root };
|
|
29640
|
+
const remember = (outcome) => {
|
|
29641
|
+
writeState(ctx, {
|
|
29642
|
+
sessionId: ctx.sessionId,
|
|
29643
|
+
status: outcome.status,
|
|
29644
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
29645
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
29646
|
+
githubLogin: outcome.githubLogin
|
|
29647
|
+
},
|
|
29648
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
29649
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
29650
|
+
repositoryRoot: root,
|
|
29651
|
+
branch: attempt.branch ?? state?.branch,
|
|
29652
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
29653
|
+
at: Date.now()
|
|
29654
|
+
});
|
|
29655
|
+
return outcome;
|
|
29656
|
+
};
|
|
29657
|
+
let challenge;
|
|
29658
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
29659
|
+
attempt.challengeId = state.challengeId;
|
|
29660
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
29661
|
+
attempt.branch = state.branch;
|
|
29662
|
+
attempt.baseSha = state.baseSha;
|
|
29663
|
+
challenge = {
|
|
29664
|
+
challengeId: state.challengeId,
|
|
29665
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
29666
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
29667
|
+
};
|
|
29668
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
29669
|
+
attempt.challengeId = state.challengeId;
|
|
29670
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
29671
|
+
const exchanged2 = await exchangeChallenge(
|
|
29672
|
+
ctx,
|
|
29673
|
+
{
|
|
29674
|
+
challengeId: state.challengeId,
|
|
29675
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
29676
|
+
githubLogin: state.githubLogin
|
|
29677
|
+
},
|
|
29678
|
+
root,
|
|
29679
|
+
deps,
|
|
29680
|
+
options.signal
|
|
29681
|
+
);
|
|
29682
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
29683
|
+
writeToken(ctx, exchanged2);
|
|
29684
|
+
return identified(exchanged2, false);
|
|
29685
|
+
} else if (!options.explicit) {
|
|
29686
|
+
return state ? outcomeFromState(state) : failure(
|
|
29687
|
+
"not_identified",
|
|
29688
|
+
"this session has not identified who started it yet",
|
|
29689
|
+
RETRY_REMEDY
|
|
29690
|
+
);
|
|
29691
|
+
} else {
|
|
29692
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
29693
|
+
if ("status" in pushed) return remember(pushed);
|
|
29694
|
+
challenge = pushed;
|
|
29695
|
+
}
|
|
29696
|
+
const verified = await pollChallenge(
|
|
29697
|
+
ctx.apiUrl,
|
|
29698
|
+
challenge.challengeId,
|
|
29699
|
+
challenge.repository,
|
|
29700
|
+
// A hook process waits only briefly for a late notice.
|
|
29701
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
29702
|
+
options.signal
|
|
29703
|
+
);
|
|
29704
|
+
if ("status" in verified) return remember(verified);
|
|
29705
|
+
const exchanged = await exchangeChallenge(
|
|
29706
|
+
ctx,
|
|
29707
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
29708
|
+
root,
|
|
29709
|
+
deps,
|
|
29710
|
+
options.signal
|
|
29711
|
+
);
|
|
29712
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
29713
|
+
writeToken(ctx, exchanged);
|
|
29714
|
+
return identified(exchanged, false);
|
|
29715
|
+
},
|
|
29716
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
29717
|
+
);
|
|
29718
|
+
}
|
|
29719
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
29720
|
+
const cached2 = cachedSessionCredential(deps);
|
|
29721
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
29722
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
29723
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
29724
|
+
let outcome;
|
|
29725
|
+
try {
|
|
29726
|
+
outcome = await ensureSessionIdentity(
|
|
29727
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
29728
|
+
deps
|
|
29729
|
+
);
|
|
29730
|
+
} catch (error) {
|
|
29731
|
+
options.signal?.throwIfAborted();
|
|
29732
|
+
if (error instanceof MachineAuthError) throw error;
|
|
29733
|
+
throw new MachineAuthError(
|
|
29734
|
+
"identity_unavailable",
|
|
29735
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
29736
|
+
);
|
|
29737
|
+
}
|
|
29738
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
29739
|
+
throw new MachineAuthError(
|
|
29740
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
29741
|
+
sessionIdentityMessage(outcome)
|
|
29742
|
+
);
|
|
29743
|
+
}
|
|
29744
|
+
|
|
28567
29745
|
// src/lib/machine-credentials.ts
|
|
29746
|
+
function sessionScoped(deps) {
|
|
29747
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
29748
|
+
}
|
|
28568
29749
|
var require3 = createRequire2(import.meta.url);
|
|
28569
29750
|
var SERVICE = "ai.primitive.prim.machine";
|
|
28570
|
-
var
|
|
29751
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
28571
29752
|
var PROFILE_FILE = "machine_profile.json";
|
|
28572
|
-
var
|
|
29753
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
28573
29754
|
var cached;
|
|
28574
29755
|
function configurationDirectory(deps) {
|
|
28575
29756
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
28576
29757
|
}
|
|
28577
29758
|
function apiUrlFor(deps) {
|
|
28578
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
29759
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
28579
29760
|
}
|
|
28580
|
-
function
|
|
28581
|
-
return
|
|
29761
|
+
function hash2(value) {
|
|
29762
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
28582
29763
|
}
|
|
28583
29764
|
function recordPath(directory, generation) {
|
|
28584
|
-
return
|
|
29765
|
+
return join14(directory, `machine_${generation}.json`);
|
|
28585
29766
|
}
|
|
28586
29767
|
function storageKey(directory, generation) {
|
|
28587
|
-
return `${
|
|
29768
|
+
return `${hash2(directory)}:${generation}`;
|
|
28588
29769
|
}
|
|
28589
29770
|
function environmentContextPath(deps, clientId) {
|
|
28590
|
-
return
|
|
29771
|
+
return join14(
|
|
28591
29772
|
configurationDirectory(deps),
|
|
28592
|
-
`machine_context_${
|
|
29773
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
28593
29774
|
);
|
|
28594
29775
|
}
|
|
28595
29776
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -28647,17 +29828,23 @@ function readEnvironmentContext(environment, deps) {
|
|
|
28647
29828
|
return void 0;
|
|
28648
29829
|
}
|
|
28649
29830
|
}
|
|
28650
|
-
function
|
|
28651
|
-
let directory =
|
|
29831
|
+
function keyringLoaderPath(start, options = {}) {
|
|
29832
|
+
let directory = start;
|
|
28652
29833
|
for (let depth = 0; depth < 5; depth++) {
|
|
28653
|
-
const loader =
|
|
28654
|
-
if (existsSync10(loader))
|
|
28655
|
-
const module2 = require3(loader);
|
|
28656
|
-
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
28657
|
-
}
|
|
29834
|
+
const loader = join14(directory, "native", "keyring.cjs");
|
|
29835
|
+
if (existsSync10(loader)) return loader;
|
|
28658
29836
|
directory = dirname7(directory);
|
|
28659
29837
|
}
|
|
28660
|
-
|
|
29838
|
+
try {
|
|
29839
|
+
createRequire2(join14(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
29840
|
+
return void 0;
|
|
29841
|
+
} catch {
|
|
29842
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
29843
|
+
}
|
|
29844
|
+
}
|
|
29845
|
+
function keyringEntry(key) {
|
|
29846
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath4(import.meta.url)));
|
|
29847
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
28661
29848
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
28662
29849
|
}
|
|
28663
29850
|
function protectPath(path, directory) {
|
|
@@ -28692,6 +29879,9 @@ function writePrivate(path, value) {
|
|
|
28692
29879
|
`, { mode: 384 });
|
|
28693
29880
|
protectPath(path, false);
|
|
28694
29881
|
}
|
|
29882
|
+
function readMachineMetadata(path) {
|
|
29883
|
+
return readPrivate(path);
|
|
29884
|
+
}
|
|
28695
29885
|
function readPrivate(path) {
|
|
28696
29886
|
let raw;
|
|
28697
29887
|
try {
|
|
@@ -28747,7 +29937,7 @@ function parseProfile(value) {
|
|
|
28747
29937
|
};
|
|
28748
29938
|
}
|
|
28749
29939
|
function readMachineProfile(deps = {}) {
|
|
28750
|
-
const value = readPrivate(
|
|
29940
|
+
const value = readPrivate(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
28751
29941
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
28752
29942
|
}
|
|
28753
29943
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -28756,7 +29946,7 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
28756
29946
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
28757
29947
|
function networkSecretBrokerKey(deps, clientId) {
|
|
28758
29948
|
const directory = configurationDirectory(deps);
|
|
28759
|
-
const path =
|
|
29949
|
+
const path = join14(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
28760
29950
|
const known = brokerKeys.get(path);
|
|
28761
29951
|
if (known) return known;
|
|
28762
29952
|
ensureDirectory(directory);
|
|
@@ -28797,7 +29987,7 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
28797
29987
|
} catch (error) {
|
|
28798
29988
|
if (error.code !== "EEXIST") throw error;
|
|
28799
29989
|
} finally {
|
|
28800
|
-
|
|
29990
|
+
rmSync8(staged, { force: true });
|
|
28801
29991
|
}
|
|
28802
29992
|
}
|
|
28803
29993
|
const key = read()?.key;
|
|
@@ -28830,7 +30020,7 @@ function environmentCredentials(deps) {
|
|
|
28830
30020
|
"conflicting_credentials",
|
|
28831
30021
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
28832
30022
|
);
|
|
28833
|
-
const generation =
|
|
30023
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
28834
30024
|
const credentials = {
|
|
28835
30025
|
clientId,
|
|
28836
30026
|
generation,
|
|
@@ -28851,12 +30041,12 @@ function environmentCredentials(deps) {
|
|
|
28851
30041
|
return {
|
|
28852
30042
|
clientId,
|
|
28853
30043
|
clientSecret,
|
|
28854
|
-
generation:
|
|
30044
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
28855
30045
|
};
|
|
28856
30046
|
}
|
|
28857
30047
|
function hasMachineConfiguration(deps = {}) {
|
|
28858
30048
|
const env = deps.env ?? process.env;
|
|
28859
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync10(
|
|
30049
|
+
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));
|
|
28860
30050
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
28861
30051
|
throw new MachineAuthError(
|
|
28862
30052
|
"conflicting_credentials",
|
|
@@ -28868,6 +30058,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
28868
30058
|
}
|
|
28869
30059
|
function machineContext(deps = {}) {
|
|
28870
30060
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
30061
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
28871
30062
|
const environment = environmentCredentials(deps);
|
|
28872
30063
|
if (environment) {
|
|
28873
30064
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -28882,6 +30073,7 @@ function machineContext(deps = {}) {
|
|
|
28882
30073
|
return profile;
|
|
28883
30074
|
}
|
|
28884
30075
|
function cachedMachineCredential(deps = {}) {
|
|
30076
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
28885
30077
|
const context = machineContext(deps);
|
|
28886
30078
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
28887
30079
|
}
|
|
@@ -28890,7 +30082,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
28890
30082
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
28891
30083
|
if (!generation) return false;
|
|
28892
30084
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
28893
|
-
return readPrivate(
|
|
30085
|
+
return readPrivate(join14(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
28894
30086
|
}
|
|
28895
30087
|
var environmentTerminal;
|
|
28896
30088
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -28954,6 +30146,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
28954
30146
|
}
|
|
28955
30147
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
28956
30148
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
30149
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
28957
30150
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
28958
30151
|
const apiUrl = apiUrlFor(deps);
|
|
28959
30152
|
const environment = environmentCredentials(deps);
|
|
@@ -28982,7 +30175,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28982
30175
|
}
|
|
28983
30176
|
}
|
|
28984
30177
|
return withFileLock(
|
|
28985
|
-
|
|
30178
|
+
join14(directory2, "credentials.lock"),
|
|
28986
30179
|
async () => {
|
|
28987
30180
|
if (machineSessionEnded(deps))
|
|
28988
30181
|
throw new MachineAuthError(
|
|
@@ -28990,7 +30183,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
28990
30183
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
28991
30184
|
true
|
|
28992
30185
|
);
|
|
28993
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
30186
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
28994
30187
|
return cached;
|
|
28995
30188
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
28996
30189
|
throw networkRejection.error;
|
|
@@ -29064,7 +30257,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29064
30257
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
29065
30258
|
try {
|
|
29066
30259
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
29067
|
-
|
|
30260
|
+
rmSync8(contextPath, { force: true });
|
|
29068
30261
|
} catch {
|
|
29069
30262
|
}
|
|
29070
30263
|
throw error;
|
|
@@ -29074,7 +30267,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29074
30267
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
29075
30268
|
try {
|
|
29076
30269
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
29077
|
-
|
|
30270
|
+
rmSync8(contextPath, { force: true });
|
|
29078
30271
|
} catch {
|
|
29079
30272
|
}
|
|
29080
30273
|
}
|
|
@@ -29088,7 +30281,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29088
30281
|
const expected = machineContext(deps);
|
|
29089
30282
|
const directory = configurationDirectory(deps);
|
|
29090
30283
|
return withFileLock(
|
|
29091
|
-
|
|
30284
|
+
join14(directory, "credentials.lock"),
|
|
29092
30285
|
async () => {
|
|
29093
30286
|
const profile = readMachineProfile(deps);
|
|
29094
30287
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -29103,7 +30296,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29103
30296
|
true
|
|
29104
30297
|
);
|
|
29105
30298
|
let record = await loadRecord(profile, deps, signal);
|
|
29106
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
30299
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
29107
30300
|
try {
|
|
29108
30301
|
const { tokens, identity } = await withMachineCooldown(
|
|
29109
30302
|
directory,
|
|
@@ -29138,7 +30331,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
29138
30331
|
await persistRecord(record, deps, signal);
|
|
29139
30332
|
} catch (error) {
|
|
29140
30333
|
if (error instanceof MachineAuthError && error.terminal)
|
|
29141
|
-
writePrivate(
|
|
30334
|
+
writePrivate(join14(directory, "machine_terminal.json"), profile.generation);
|
|
29142
30335
|
throw error;
|
|
29143
30336
|
}
|
|
29144
30337
|
}
|
|
@@ -29167,17 +30360,23 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
|
29167
30360
|
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
29168
30361
|
});
|
|
29169
30362
|
}
|
|
30363
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
30364
|
+
ensureDirectory(directory);
|
|
30365
|
+
}
|
|
30366
|
+
function writeMachineMetadata(path, value) {
|
|
30367
|
+
writePrivate(path, value);
|
|
30368
|
+
}
|
|
29170
30369
|
|
|
29171
30370
|
// src/lib/credentials.ts
|
|
29172
30371
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
29173
|
-
var TOKEN_FILE_PATH =
|
|
29174
|
-
var REFRESH_TOKEN_PATH =
|
|
29175
|
-
var TOKEN_EXPIRES_PATH =
|
|
29176
|
-
var TERMINAL_REFRESH_PATH =
|
|
29177
|
-
var CREDENTIAL_METADATA_PATH =
|
|
29178
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
29179
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
29180
|
-
var CREDENTIAL_LOCK_PATH =
|
|
30372
|
+
var TOKEN_FILE_PATH = join15(CONFIG_DIRECTORY, "token");
|
|
30373
|
+
var REFRESH_TOKEN_PATH = join15(CONFIG_DIRECTORY, "refresh_token");
|
|
30374
|
+
var TOKEN_EXPIRES_PATH = join15(CONFIG_DIRECTORY, "token_expires_at");
|
|
30375
|
+
var TERMINAL_REFRESH_PATH = join15(CONFIG_DIRECTORY, "refresh_terminal");
|
|
30376
|
+
var CREDENTIAL_METADATA_PATH = join15(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
30377
|
+
var CREDENTIAL_FAMILY_PATH = join15(CONFIG_DIRECTORY, "credential_family.json");
|
|
30378
|
+
var CREDENTIAL_MIGRATION_PATH = join15(CONFIG_DIRECTORY, "credential_migration.json");
|
|
30379
|
+
var CREDENTIAL_LOCK_PATH = join15(CONFIG_DIRECTORY, "credentials.lock");
|
|
29181
30380
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
29182
30381
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
29183
30382
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
@@ -29205,22 +30404,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
29205
30404
|
);
|
|
29206
30405
|
if (metadata.state === "legacy_broker") {
|
|
29207
30406
|
if (metadata.metadata) {
|
|
29208
|
-
const
|
|
29209
|
-
if (!
|
|
30407
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
30408
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
29210
30409
|
return void 0;
|
|
29211
30410
|
}
|
|
29212
30411
|
}
|
|
29213
30412
|
return { token: stored, source: "token_file" };
|
|
29214
30413
|
}
|
|
29215
30414
|
if (metadata.state === "invalid") return void 0;
|
|
29216
|
-
const
|
|
29217
|
-
if (!
|
|
30415
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
30416
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
29218
30417
|
return void 0;
|
|
29219
30418
|
}
|
|
29220
30419
|
return { token: stored, source: "token_file" };
|
|
29221
30420
|
}
|
|
29222
30421
|
function credentialFingerprint(value) {
|
|
29223
|
-
return
|
|
30422
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
29224
30423
|
}
|
|
29225
30424
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
29226
30425
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -29314,7 +30513,7 @@ function jwtExpiresAt(token) {
|
|
|
29314
30513
|
// src/daemon/client-instance-id.ts
|
|
29315
30514
|
import { randomBytes as randomBytes5 } from "crypto";
|
|
29316
30515
|
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync12 } from "fs";
|
|
29317
|
-
import { join as
|
|
30516
|
+
import { join as join16 } from "path";
|
|
29318
30517
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
29319
30518
|
var INSTANCE_FILE_MODE = 384;
|
|
29320
30519
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -29365,8 +30564,8 @@ function atomicWrite(path, value) {
|
|
|
29365
30564
|
}
|
|
29366
30565
|
async function getOrCreateClientInstanceId(options) {
|
|
29367
30566
|
const configDir = options.configDir;
|
|
29368
|
-
const path =
|
|
29369
|
-
const lockPath =
|
|
30567
|
+
const path = join16(configDir, "client_instance_id");
|
|
30568
|
+
const lockPath = join16(configDir, "client-instance.lock");
|
|
29370
30569
|
ensurePrivateConfigDirectory(configDir);
|
|
29371
30570
|
return withFileLock(
|
|
29372
30571
|
lockPath,
|
|
@@ -29410,52 +30609,11 @@ async function ingestUploaderHeaders() {
|
|
|
29410
30609
|
return headers;
|
|
29411
30610
|
}
|
|
29412
30611
|
|
|
29413
|
-
// src/lib/terminal-safe.ts
|
|
29414
|
-
function replaceIsolatedSurrogates(value) {
|
|
29415
|
-
let out = "";
|
|
29416
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
29417
|
-
const unit = value.charCodeAt(index);
|
|
29418
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
29419
|
-
const next = value.charCodeAt(index + 1);
|
|
29420
|
-
if (next >= 56320 && next <= 57343) {
|
|
29421
|
-
out += value[index] + value[index + 1];
|
|
29422
|
-
index += 1;
|
|
29423
|
-
} else {
|
|
29424
|
-
out += "\uFFFD";
|
|
29425
|
-
}
|
|
29426
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
29427
|
-
out += "\uFFFD";
|
|
29428
|
-
} else {
|
|
29429
|
-
out += value[index];
|
|
29430
|
-
}
|
|
29431
|
-
}
|
|
29432
|
-
return out;
|
|
29433
|
-
}
|
|
29434
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
29435
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
29436
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
29437
|
-
point === 1564 || // Arabic letter mark
|
|
29438
|
-
point === 6158 || // Mongolian vowel separator
|
|
29439
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
29440
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
29441
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
29442
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
29443
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
29444
|
-
point >= 917504 && point <= 917631;
|
|
29445
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
29446
|
-
}
|
|
29447
|
-
function terminalSafeText(value) {
|
|
29448
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
29449
|
-
}
|
|
29450
|
-
function terminalSafeLine(value) {
|
|
29451
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
29452
|
-
}
|
|
29453
|
-
|
|
29454
30612
|
// src/client.ts
|
|
29455
30613
|
var CONFIG_DIR_MODE = 448;
|
|
29456
30614
|
var CREDENTIAL_FILE_MODE = 384;
|
|
29457
30615
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
29458
|
-
var
|
|
30616
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
29459
30617
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
29460
30618
|
function authExpiredMessage() {
|
|
29461
30619
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
@@ -29472,7 +30630,7 @@ function getSiteUrl() {
|
|
|
29472
30630
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
29473
30631
|
}
|
|
29474
30632
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
29475
|
-
return primApiUrl?.trim() ||
|
|
30633
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
29476
30634
|
}
|
|
29477
30635
|
function expiresAtFor(token, expiresIn) {
|
|
29478
30636
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
@@ -29488,7 +30646,7 @@ function atomicWrite2(path, content2) {
|
|
|
29488
30646
|
}
|
|
29489
30647
|
function removeCredentialFile(path) {
|
|
29490
30648
|
if (!existsSync11(path)) return false;
|
|
29491
|
-
|
|
30649
|
+
rmSync9(path, { force: true });
|
|
29492
30650
|
return true;
|
|
29493
30651
|
}
|
|
29494
30652
|
function getTokenExpiresAt() {
|
|
@@ -29503,23 +30661,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
29503
30661
|
const expiresAt = getTokenExpiresAt();
|
|
29504
30662
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
29505
30663
|
}
|
|
29506
|
-
function refreshFingerprint(
|
|
29507
|
-
return
|
|
30664
|
+
function refreshFingerprint(refreshToken3) {
|
|
30665
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
29508
30666
|
}
|
|
29509
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
30667
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
29510
30668
|
return {
|
|
29511
30669
|
version: 1,
|
|
29512
30670
|
family: "legacy_broker",
|
|
29513
30671
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29514
|
-
refreshTokenHash: refreshFingerprint(
|
|
30672
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29515
30673
|
};
|
|
29516
30674
|
}
|
|
29517
|
-
function credentialFamilyMetadata(accessToken,
|
|
30675
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
29518
30676
|
const hashes = {
|
|
29519
30677
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29520
|
-
refreshTokenHash: refreshFingerprint(
|
|
30678
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29521
30679
|
};
|
|
29522
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
30680
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
29523
30681
|
}
|
|
29524
30682
|
function writeCredentialMigrationSentinel() {
|
|
29525
30683
|
atomicWrite2(
|
|
@@ -29531,11 +30689,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
29531
30689
|
`
|
|
29532
30690
|
);
|
|
29533
30691
|
}
|
|
29534
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
29535
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
30692
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
30693
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
29536
30694
|
return { state: "invalid" };
|
|
29537
30695
|
}
|
|
29538
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30696
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29539
30697
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
29540
30698
|
return { state: "invalid" };
|
|
29541
30699
|
}
|
|
@@ -29552,17 +30710,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
29552
30710
|
const metadata = readStoredCredentialMetadata();
|
|
29553
30711
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
29554
30712
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
29555
|
-
const
|
|
29556
|
-
if (!(accessToken &&
|
|
29557
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30713
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
30714
|
+
if (!(accessToken && refreshToken3)) return;
|
|
30715
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29558
30716
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29559
30717
|
`);
|
|
29560
30718
|
}
|
|
29561
30719
|
function terminalFingerprint() {
|
|
29562
30720
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
29563
30721
|
}
|
|
29564
|
-
function writeTerminalFingerprint(
|
|
29565
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
30722
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
30723
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
29566
30724
|
`);
|
|
29567
30725
|
}
|
|
29568
30726
|
function clearTerminalFingerprint() {
|
|
@@ -29571,20 +30729,20 @@ function clearTerminalFingerprint() {
|
|
|
29571
30729
|
function isSessionEnded() {
|
|
29572
30730
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
29573
30731
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
29574
|
-
const
|
|
30732
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
29575
30733
|
const ended = terminalFingerprint();
|
|
29576
|
-
return Boolean(
|
|
30734
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
29577
30735
|
}
|
|
29578
30736
|
function withCredentialLock(operation, options = {}) {
|
|
29579
30737
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
29580
30738
|
}
|
|
29581
30739
|
function commitCredentialsUnlocked(credentials) {
|
|
29582
30740
|
const accessToken = credentials.accessToken.trim();
|
|
29583
|
-
const
|
|
29584
|
-
if (!accessToken || !
|
|
30741
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
30742
|
+
if (!accessToken || !refreshToken3) {
|
|
29585
30743
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
29586
30744
|
}
|
|
29587
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
30745
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
29588
30746
|
if (credentials.metadata !== void 0) {
|
|
29589
30747
|
preserveMarkerlessLegacyGeneration();
|
|
29590
30748
|
writeCredentialMigrationSentinel();
|
|
@@ -29592,10 +30750,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
29592
30750
|
`);
|
|
29593
30751
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
29594
30752
|
`);
|
|
29595
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30753
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29596
30754
|
`);
|
|
29597
30755
|
} else {
|
|
29598
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30756
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29599
30757
|
`);
|
|
29600
30758
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29601
30759
|
`);
|
|
@@ -29632,15 +30790,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
29632
30790
|
`
|
|
29633
30791
|
);
|
|
29634
30792
|
}
|
|
29635
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
30793
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
29636
30794
|
const current = readStoredCredentialMetadata();
|
|
29637
30795
|
if (expected.state === "legacy_broker") {
|
|
29638
30796
|
if (current.state !== "legacy_broker") return false;
|
|
29639
30797
|
if (!expected.metadata) return current.metadata === void 0;
|
|
29640
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
30798
|
+
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;
|
|
29641
30799
|
}
|
|
29642
30800
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
29643
|
-
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(
|
|
30801
|
+
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;
|
|
29644
30802
|
}
|
|
29645
30803
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
29646
30804
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -29809,7 +30967,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
29809
30967
|
);
|
|
29810
30968
|
}
|
|
29811
30969
|
var _refreshInFlight;
|
|
29812
|
-
function
|
|
30970
|
+
function refreshToken2(options = {}) {
|
|
29813
30971
|
if (hasMachineConfiguration())
|
|
29814
30972
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
29815
30973
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -29947,7 +31105,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29947
31105
|
if (response.status === 401)
|
|
29948
31106
|
throw new HttpError(
|
|
29949
31107
|
401,
|
|
29950
|
-
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(
|
|
31108
|
+
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(
|
|
29951
31109
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
29952
31110
|
)
|
|
29953
31111
|
);
|
|
@@ -29968,7 +31126,7 @@ async function request2(method, path, body, options) {
|
|
|
29968
31126
|
let refreshAttempted = false;
|
|
29969
31127
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
29970
31128
|
refreshAttempted = true;
|
|
29971
|
-
const token = await
|
|
31129
|
+
const token = await refreshToken2({
|
|
29972
31130
|
signal: options?.signal,
|
|
29973
31131
|
quiet: options?.quietRefresh
|
|
29974
31132
|
});
|
|
@@ -29987,7 +31145,7 @@ async function request2(method, path, body, options) {
|
|
|
29987
31145
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
29988
31146
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
29989
31147
|
refreshAttempted = true;
|
|
29990
|
-
retryToken = await
|
|
31148
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
29991
31149
|
}
|
|
29992
31150
|
if (retryToken) {
|
|
29993
31151
|
_cachedCredential = {
|
|
@@ -30305,7 +31463,7 @@ function parseAgent(argv) {
|
|
|
30305
31463
|
|
|
30306
31464
|
// src/hooks/redact.ts
|
|
30307
31465
|
import { existsSync as existsSync12, readFileSync as readFileSync14, statSync as statSync3 } from "fs";
|
|
30308
|
-
import { join as
|
|
31466
|
+
import { join as join18 } from "path";
|
|
30309
31467
|
import { Worker } from "worker_threads";
|
|
30310
31468
|
|
|
30311
31469
|
// src/lib/ansi.ts
|
|
@@ -30521,7 +31679,7 @@ function approvalSummary(evidence, preview) {
|
|
|
30521
31679
|
// src/commands/cursor-install.ts
|
|
30522
31680
|
import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
|
|
30523
31681
|
import { homedir as homedir4 } from "os";
|
|
30524
|
-
import { isAbsolute as isAbsolute5, join as
|
|
31682
|
+
import { isAbsolute as isAbsolute5, join as join20 } from "path";
|
|
30525
31683
|
|
|
30526
31684
|
// src/lib/preflight-host.ts
|
|
30527
31685
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
@@ -30529,7 +31687,7 @@ import { execFileSync as execFileSync5 } from "child_process";
|
|
|
30529
31687
|
// src/commands/claude-install.ts
|
|
30530
31688
|
import { existsSync as existsSync13, lstatSync as lstatSync8, readFileSync as readFileSync15 } from "fs";
|
|
30531
31689
|
import { homedir as homedir3 } from "os";
|
|
30532
|
-
import { join as
|
|
31690
|
+
import { join as join19 } from "path";
|
|
30533
31691
|
var CAPTURE_BIN = "prim-hook";
|
|
30534
31692
|
var GATE_BIN = "prim-pre-tool-use";
|
|
30535
31693
|
var POST_TOOL_USE_BIN = "prim-post-tool-use";
|
|
@@ -30538,7 +31696,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
30538
31696
|
var STATUSLINE_BIN = "prim-statusline";
|
|
30539
31697
|
var STATUSLINE_ARGS = "";
|
|
30540
31698
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
30541
|
-
var USER_SCOPE_PATH =
|
|
31699
|
+
var USER_SCOPE_PATH = join19(homedir3(), ".claude", "settings.json");
|
|
30542
31700
|
function projectRoot() {
|
|
30543
31701
|
return gitToplevel() ?? process.cwd();
|
|
30544
31702
|
}
|
|
@@ -30618,11 +31776,11 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
|
|
|
30618
31776
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
30619
31777
|
if (explicit && isAbsolute5(explicit)) return explicit;
|
|
30620
31778
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
30621
|
-
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return
|
|
30622
|
-
return
|
|
31779
|
+
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join20(xdg, "cursor");
|
|
31780
|
+
return join20(home, ".cursor");
|
|
30623
31781
|
}
|
|
30624
31782
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
30625
|
-
return scope === "user" ?
|
|
31783
|
+
return scope === "user" ? join20(cursorConfigDirectory(), "hooks.json") : join20(root, ".cursor", "hooks.json");
|
|
30626
31784
|
}
|
|
30627
31785
|
function plainObject(value) {
|
|
30628
31786
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -30774,7 +31932,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
|
|
|
30774
31932
|
}
|
|
30775
31933
|
|
|
30776
31934
|
// src/hooks/normalize.ts
|
|
30777
|
-
import { createHash as
|
|
31935
|
+
import { createHash as createHash10 } from "crypto";
|
|
30778
31936
|
import { realpathSync as realpathSync3 } from "fs";
|
|
30779
31937
|
import { isAbsolute as isAbsolute6, resolve as resolve5 } from "path";
|
|
30780
31938
|
var HERMES_EVENT_MAP = {
|
|
@@ -30819,7 +31977,7 @@ function requiredId(value, field) {
|
|
|
30819
31977
|
}
|
|
30820
31978
|
function cursorToolUseId(value) {
|
|
30821
31979
|
if (SAFE_CORRELATION_ID_RE.test(value)) return value;
|
|
30822
|
-
return `cursor:tool:v1:${
|
|
31980
|
+
return `cursor:tool:v1:${createHash10("sha256").update(value).digest("hex")}`;
|
|
30823
31981
|
}
|
|
30824
31982
|
function workspaceCandidates(value) {
|
|
30825
31983
|
if (!Array.isArray(value)) return [];
|
|
@@ -30916,7 +32074,7 @@ function normalizeEnvelope(parsed, agent2) {
|
|
|
30916
32074
|
]);
|
|
30917
32075
|
return {
|
|
30918
32076
|
...parsed,
|
|
30919
|
-
tool_use_id: `codex:fallback:v1:${
|
|
32077
|
+
tool_use_id: `codex:fallback:v1:${createHash10("sha256").update(stableToolIdentity).digest("hex")}`
|
|
30920
32078
|
};
|
|
30921
32079
|
}
|
|
30922
32080
|
return parsed;
|
|
@@ -37384,7 +38542,7 @@ var TokenGroup = class {
|
|
|
37384
38542
|
}
|
|
37385
38543
|
token(input, stack) {
|
|
37386
38544
|
let { parser: parser3 } = stack.p;
|
|
37387
|
-
|
|
38545
|
+
readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
|
|
37388
38546
|
}
|
|
37389
38547
|
};
|
|
37390
38548
|
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
|
|
@@ -37398,7 +38556,7 @@ var LocalTokenGroup = class {
|
|
|
37398
38556
|
let start = input.pos, skipped = 0;
|
|
37399
38557
|
for (; ; ) {
|
|
37400
38558
|
let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
|
|
37401
|
-
|
|
38559
|
+
readToken2(this.data, input, stack, 0, this.data, this.precTable);
|
|
37402
38560
|
if (input.token.value > -1)
|
|
37403
38561
|
break;
|
|
37404
38562
|
if (this.elseToken == null)
|
|
@@ -37431,7 +38589,7 @@ var ExternalTokenizer = class {
|
|
|
37431
38589
|
this.extend = !!options.extend;
|
|
37432
38590
|
}
|
|
37433
38591
|
};
|
|
37434
|
-
function
|
|
38592
|
+
function readToken2(data, input, stack, group, precTable, precOffset) {
|
|
37435
38593
|
let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
|
|
37436
38594
|
scan: for (; ; ) {
|
|
37437
38595
|
if ((groupMask & data[state]) == 0)
|
|
@@ -39244,7 +40402,7 @@ var newline2 = 10;
|
|
|
39244
40402
|
var carriageReturn = 13;
|
|
39245
40403
|
var space2 = 32;
|
|
39246
40404
|
var tab = 9;
|
|
39247
|
-
var
|
|
40405
|
+
var hash3 = 35;
|
|
39248
40406
|
var parenOpen = 40;
|
|
39249
40407
|
var dot2 = 46;
|
|
39250
40408
|
var braceOpen = 123;
|
|
@@ -39297,7 +40455,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
|
|
|
39297
40455
|
input.advance();
|
|
39298
40456
|
spaces2++;
|
|
39299
40457
|
}
|
|
39300
|
-
if (input.next == newline2 || input.next == carriageReturn || input.next ==
|
|
40458
|
+
if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
|
|
39301
40459
|
input.acceptToken(blankLineStart, -spaces2);
|
|
39302
40460
|
} else if (isLineBreak(input.next)) {
|
|
39303
40461
|
input.acceptToken(newline$1, 1);
|
|
@@ -39316,7 +40474,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
|
|
|
39316
40474
|
input.advance();
|
|
39317
40475
|
chars++;
|
|
39318
40476
|
}
|
|
39319
|
-
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next !=
|
|
40477
|
+
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
|
|
39320
40478
|
if (depth < context.indent) input.acceptToken(dedent, -chars);
|
|
39321
40479
|
else input.acceptToken(indent);
|
|
39322
40480
|
}
|
|
@@ -39390,7 +40548,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
|
|
|
39390
40548
|
for (let off = 0; ; off++) {
|
|
39391
40549
|
let next = input.peek(off);
|
|
39392
40550
|
if (next == space2 || next == tab) continue;
|
|
39393
|
-
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next !=
|
|
40551
|
+
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
|
|
39394
40552
|
input.acceptToken(printKeyword);
|
|
39395
40553
|
return;
|
|
39396
40554
|
}
|
|
@@ -40644,7 +41802,7 @@ function unverifiedResult(message) {
|
|
|
40644
41802
|
}
|
|
40645
41803
|
|
|
40646
41804
|
// src/hooks/preflight-v4.ts
|
|
40647
|
-
import { createHash as
|
|
41805
|
+
import { createHash as createHash11 } from "crypto";
|
|
40648
41806
|
import { setTimeout as delay } from "timers/promises";
|
|
40649
41807
|
var PREFLIGHT_PROTOCOL_VERSION2 = 4;
|
|
40650
41808
|
var PREFLIGHT_WAIT_MS = 24e4;
|
|
@@ -40667,7 +41825,7 @@ function toolInputDigest(toolName, input) {
|
|
|
40667
41825
|
}
|
|
40668
41826
|
throw new Error("Tool input has no stable JSON identity");
|
|
40669
41827
|
}
|
|
40670
|
-
return
|
|
41828
|
+
return createHash11("sha256").update(canonical({ toolName, input: input ?? null })).digest("hex");
|
|
40671
41829
|
}
|
|
40672
41830
|
function isUnidentifiedPause(response) {
|
|
40673
41831
|
return response.state === "paused" && (response.verdict === "block" || response.verdict === "unavailable") && response.checkId === void 0 && response.evaluationId === void 0;
|