@primitive.ai/prim 0.1.0-alpha.125 → 0.1.0-alpha.127
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 +140 -1
- package/SKILL.md +6 -1
- package/dist/{chunk-JFWJN2ME.js → chunk-72NIZMZN.js} +114 -5
- package/dist/{chunk-2BEUR3DU.js → chunk-A5VTE43F.js} +2 -2
- package/dist/{chunk-6OPSSJHO.js → chunk-C4QNBSWB.js} +24 -9
- package/dist/{chunk-BFYJLI7V.js → chunk-F3FDVHR7.js} +1 -1
- package/dist/{chunk-YP4OXKNX.js → chunk-H6X52UVF.js} +1 -1
- package/dist/{chunk-ND6TYHNI.js → chunk-H74RDXKP.js} +2 -2
- package/dist/{chunk-NJBN3WXF.js → chunk-HZI5PBN4.js} +785 -154
- package/dist/{chunk-FYYHBOOM.js → chunk-JCKOW45X.js} +2 -2
- package/dist/{chunk-DT7E3SD5.js → chunk-KFRGVHGB.js} +4 -4
- package/dist/{chunk-TI37ME2D.js → chunk-L6IL4N6Y.js} +16 -7
- package/dist/{chunk-HPA7RGSZ.js → chunk-MGKSZSTV.js} +7 -8
- package/dist/{chunk-ZKXNJB6U.js → chunk-NVDPKW7Z.js} +69 -29
- package/dist/{chunk-NBNQI3YJ.js → chunk-O65UVJZH.js} +6 -3
- package/dist/{chunk-74DQDWLW.js → chunk-R4EYLEIK.js} +7 -2
- package/dist/{chunk-R35M4RCY.js → chunk-RV3JFSMX.js} +4 -4
- package/dist/{chunk-PPZ56EVJ.js → chunk-TNWI3JWK.js} +1 -1
- package/dist/{chunk-6KXQQ7CQ.js → chunk-URYZDQFH.js} +3 -3
- package/dist/{chunk-L32WYFJT.js → chunk-UUQT5GMO.js} +135 -12
- package/dist/{chunk-EZXIKEMA.js → chunk-VVFVENU4.js} +6 -4
- package/dist/{chunk-O73J3KQQ.js → chunk-WGTUNUIS.js} +5 -2
- package/dist/daemon/server.js +805 -218
- package/dist/hook-runtime/daemon/server.js +805 -218
- package/dist/hook-runtime/hooks/post-commit.js +286 -59
- package/dist/hook-runtime/hooks/post-rewrite.js +278 -51
- package/dist/hook-runtime/hooks/post-tool-use.js +672 -194
- package/dist/hook-runtime/hooks/pre-commit.js +536 -88
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +616 -165
- package/dist/hook-runtime/hooks/prim-hook.js +642 -167
- package/dist/hook-runtime/hooks/session-end.js +263 -47
- package/dist/hook-runtime/hooks/session-start.js +1103 -476
- package/dist/hook-runtime/index.js +3645 -2120
- package/dist/hook-runtime/statusline-main.js +257 -29
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +15 -15
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +14 -15
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +49 -18
- package/dist/index.js +1014 -271
- package/dist/statusline-main.js +257 -29
- package/package.json +1 -1
|
@@ -81,6 +81,17 @@ function publicDecisionResponse(value) {
|
|
|
81
81
|
return replace(projected);
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
// src/lib/cloud-env.ts
|
|
85
|
+
function isClaudeCloudSession(env = process.env) {
|
|
86
|
+
return env.CLAUDE_CODE_REMOTE === "true";
|
|
87
|
+
}
|
|
88
|
+
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';
|
|
89
|
+
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';
|
|
90
|
+
function cloudSetupPointer(message, env = process.env) {
|
|
91
|
+
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
92
|
+
}
|
|
93
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
94
|
+
|
|
84
95
|
// src/client.ts
|
|
85
96
|
import { createHash as createHash5 } from "crypto";
|
|
86
97
|
import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
|
|
@@ -172,8 +183,17 @@ import { join as join7 } from "path";
|
|
|
172
183
|
|
|
173
184
|
// src/lib/machine-credentials.ts
|
|
174
185
|
import { execFileSync } from "child_process";
|
|
175
|
-
import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
|
|
176
|
-
import {
|
|
186
|
+
import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
|
|
187
|
+
import {
|
|
188
|
+
chmodSync,
|
|
189
|
+
existsSync as existsSync3,
|
|
190
|
+
linkSync,
|
|
191
|
+
lstatSync as lstatSync3,
|
|
192
|
+
mkdirSync as mkdirSync3,
|
|
193
|
+
readFileSync as readFileSync5,
|
|
194
|
+
rmSync as rmSync5,
|
|
195
|
+
writeFileSync as writeFileSync3
|
|
196
|
+
} from "fs";
|
|
177
197
|
import { createRequire } from "module";
|
|
178
198
|
import { dirname as dirname4, join as join6 } from "path";
|
|
179
199
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
@@ -381,6 +401,36 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
|
381
401
|
"fi; fi; "
|
|
382
402
|
].join("");
|
|
383
403
|
|
|
404
|
+
// src/lib/loopback-fetch.ts
|
|
405
|
+
import { request } from "http";
|
|
406
|
+
import { Readable } from "stream";
|
|
407
|
+
function loopbackFetch(url, init = {}) {
|
|
408
|
+
const target = new URL(url);
|
|
409
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
410
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
411
|
+
return new Promise((resolve3, reject) => {
|
|
412
|
+
const outgoing = request(
|
|
413
|
+
target,
|
|
414
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
415
|
+
(incoming) => {
|
|
416
|
+
try {
|
|
417
|
+
const headers = new Headers();
|
|
418
|
+
for (const [name, value] of Object.entries(incoming.headers))
|
|
419
|
+
if (typeof value === "string") headers.set(name, value);
|
|
420
|
+
const status = incoming.statusCode ?? 502;
|
|
421
|
+
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
422
|
+
resolve3(new Response(body, { status, headers }));
|
|
423
|
+
} catch (error) {
|
|
424
|
+
incoming.destroy();
|
|
425
|
+
reject(error);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
);
|
|
429
|
+
outgoing.once("error", reject);
|
|
430
|
+
outgoing.end(init.body);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
384
434
|
// src/lib/workos-connect.ts
|
|
385
435
|
var TOKEN_PATH = "/oauth2/token";
|
|
386
436
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -576,9 +626,19 @@ function parseMachineConfiguration(value) {
|
|
|
576
626
|
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
577
627
|
};
|
|
578
628
|
}
|
|
629
|
+
function rejectedCredentialsMessage(message, env = process.env) {
|
|
630
|
+
return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
631
|
+
}
|
|
579
632
|
function machineSignal(signal) {
|
|
580
633
|
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
581
634
|
}
|
|
635
|
+
function hostOf(url) {
|
|
636
|
+
try {
|
|
637
|
+
return new URL(url).hostname;
|
|
638
|
+
} catch {
|
|
639
|
+
return "Primitive";
|
|
640
|
+
}
|
|
641
|
+
}
|
|
582
642
|
async function fetchMachine(url, options, fetchImpl) {
|
|
583
643
|
try {
|
|
584
644
|
return await fetchImpl(url, options);
|
|
@@ -586,7 +646,9 @@ async function fetchMachine(url, options, fetchImpl) {
|
|
|
586
646
|
options.signal?.throwIfAborted();
|
|
587
647
|
throw new MachineAuthError(
|
|
588
648
|
"authentication_unavailable",
|
|
589
|
-
|
|
649
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
650
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
651
|
+
isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
590
652
|
);
|
|
591
653
|
}
|
|
592
654
|
}
|
|
@@ -613,8 +675,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
|
613
675
|
);
|
|
614
676
|
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
615
677
|
}
|
|
616
|
-
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
617
|
-
|
|
678
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
679
|
+
const network = options.secretInjection === "network";
|
|
680
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
618
681
|
throw new MachineAuthError(
|
|
619
682
|
"invalid_credentials",
|
|
620
683
|
"A machine client ID and secret are required.",
|
|
@@ -628,11 +691,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
628
691
|
redirect: "error",
|
|
629
692
|
signal: machineSignal(signal),
|
|
630
693
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
client_secret: clientSecret
|
|
635
|
-
|
|
694
|
+
// With a network secret the agent proxy authenticates the client with
|
|
695
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
696
|
+
body: new URLSearchParams(
|
|
697
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
698
|
+
)
|
|
636
699
|
},
|
|
637
700
|
fetchImpl
|
|
638
701
|
);
|
|
@@ -640,7 +703,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
640
703
|
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
641
704
|
throw new MachineAuthError(
|
|
642
705
|
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
643
|
-
terminal ?
|
|
706
|
+
terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
|
|
707
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
708
|
+
) : "The machine token service is temporarily unavailable.",
|
|
644
709
|
terminal,
|
|
645
710
|
terminal ? void 0 : machineRetryAt(response)
|
|
646
711
|
);
|
|
@@ -660,6 +725,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
660
725
|
} catch {
|
|
661
726
|
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
662
727
|
}
|
|
728
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
729
|
+
throw new MachineAuthError(
|
|
730
|
+
"token_client_mismatch",
|
|
731
|
+
"The token service issued a token for another machine client."
|
|
732
|
+
);
|
|
663
733
|
if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
|
|
664
734
|
throw new MachineAuthError(
|
|
665
735
|
"token_identity_mismatch",
|
|
@@ -705,12 +775,51 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
|
|
|
705
775
|
const terminal = response.status === 401 || response.status === 403;
|
|
706
776
|
throw new MachineAuthError(
|
|
707
777
|
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
708
|
-
terminal ?
|
|
778
|
+
terminal ? rejectedCredentialsMessage(
|
|
779
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
780
|
+
) : "Machine verification is temporarily unavailable.",
|
|
709
781
|
terminal
|
|
710
782
|
);
|
|
711
783
|
}
|
|
712
784
|
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
713
785
|
}
|
|
786
|
+
function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
|
|
787
|
+
const rejected = () => new MachineAuthError(
|
|
788
|
+
"network_token_rejected",
|
|
789
|
+
`Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
|
|
790
|
+
true
|
|
791
|
+
);
|
|
792
|
+
if (status === 401 || status === 403) throw rejected();
|
|
793
|
+
if (status < 200 || status > 299)
|
|
794
|
+
throw new MachineAuthError(
|
|
795
|
+
"verification_unavailable",
|
|
796
|
+
"Machine verification is temporarily unavailable."
|
|
797
|
+
);
|
|
798
|
+
let data;
|
|
799
|
+
try {
|
|
800
|
+
data = machineRecord(value);
|
|
801
|
+
} catch {
|
|
802
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
803
|
+
}
|
|
804
|
+
if (data.authenticated !== true) throw rejected();
|
|
805
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
806
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
807
|
+
throw new MachineAuthError(
|
|
808
|
+
"network_secret_mismatch",
|
|
809
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
810
|
+
true
|
|
811
|
+
);
|
|
812
|
+
return parseMachineIdentity(data, clientId);
|
|
813
|
+
}
|
|
814
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
815
|
+
const response = await fetchMachine(
|
|
816
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
817
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
818
|
+
fetchImpl
|
|
819
|
+
);
|
|
820
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
821
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
822
|
+
}
|
|
714
823
|
|
|
715
824
|
// src/lib/paths.ts
|
|
716
825
|
import { homedir } from "os";
|
|
@@ -742,6 +851,11 @@ function primConfigDirectory(options = {}) {
|
|
|
742
851
|
|
|
743
852
|
// src/lib/machine-broker.ts
|
|
744
853
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
854
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
855
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
856
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
857
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
858
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
745
859
|
var IDLE_MS = 5 * 6e4;
|
|
746
860
|
function descriptorPath(directory, generation) {
|
|
747
861
|
return join4(directory, `machine_broker_${generation}.json`);
|
|
@@ -757,8 +871,8 @@ function readDescriptor(path) {
|
|
|
757
871
|
return void 0;
|
|
758
872
|
}
|
|
759
873
|
}
|
|
760
|
-
function signature(secret, nonce, body) {
|
|
761
|
-
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
874
|
+
function signature(secret, nonce, body, purpose) {
|
|
875
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
762
876
|
}
|
|
763
877
|
function matches(left, right) {
|
|
764
878
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
@@ -773,10 +887,9 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
773
887
|
observedTokenHash: tokenHash(options.observedToken),
|
|
774
888
|
timestamp: Date.now()
|
|
775
889
|
});
|
|
776
|
-
const response = await
|
|
890
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
777
891
|
method: "POST",
|
|
778
892
|
body,
|
|
779
|
-
redirect: "error",
|
|
780
893
|
signal: options.signal,
|
|
781
894
|
headers: {
|
|
782
895
|
"Content-Type": "application/json",
|
|
@@ -807,6 +920,15 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
807
920
|
);
|
|
808
921
|
return credential;
|
|
809
922
|
}
|
|
923
|
+
function brokerEnvironment(options) {
|
|
924
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
925
|
+
return {
|
|
926
|
+
...options.env,
|
|
927
|
+
PRIM_API_URL: options.apiUrl,
|
|
928
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
929
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
930
|
+
};
|
|
931
|
+
}
|
|
810
932
|
async function acquireBrokerCredential(options) {
|
|
811
933
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
812
934
|
const existing = readDescriptor(path);
|
|
@@ -818,15 +940,28 @@ async function acquireBrokerCredential(options) {
|
|
|
818
940
|
if (error instanceof MachineAuthError) throw error;
|
|
819
941
|
}
|
|
820
942
|
}
|
|
821
|
-
const descriptor = await
|
|
943
|
+
const descriptor = await ensureBroker(options);
|
|
944
|
+
try {
|
|
945
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
946
|
+
} catch (error) {
|
|
947
|
+
options.signal.throwIfAborted();
|
|
948
|
+
if (error instanceof MachineAuthError) throw error;
|
|
949
|
+
throw new MachineAuthError(
|
|
950
|
+
"broker_unavailable",
|
|
951
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
952
|
+
);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
async function ensureBroker(options) {
|
|
956
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
957
|
+
return withFileLock(
|
|
822
958
|
join4(options.directory, "machine-broker.lock"),
|
|
823
959
|
async () => {
|
|
824
960
|
const current = readDescriptor(path);
|
|
825
961
|
if (current) {
|
|
826
962
|
try {
|
|
827
|
-
const response = await
|
|
828
|
-
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
829
|
-
redirect: "error"
|
|
963
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
964
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
830
965
|
});
|
|
831
966
|
if (response.ok && await response.text() === current.nonce) return current;
|
|
832
967
|
} catch {
|
|
@@ -845,7 +980,7 @@ async function acquireBrokerCredential(options) {
|
|
|
845
980
|
detached: true,
|
|
846
981
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
847
982
|
windowsHide: true,
|
|
848
|
-
env:
|
|
983
|
+
env: brokerEnvironment(options)
|
|
849
984
|
});
|
|
850
985
|
let settled = false;
|
|
851
986
|
const finish = (error) => {
|
|
@@ -897,27 +1032,93 @@ async function acquireBrokerCredential(options) {
|
|
|
897
1032
|
},
|
|
898
1033
|
{ signal: options.signal }
|
|
899
1034
|
);
|
|
1035
|
+
}
|
|
1036
|
+
async function forwardOnce(descriptor, environment, request3, signal) {
|
|
1037
|
+
const body = JSON.stringify({
|
|
1038
|
+
generation: environment.generation,
|
|
1039
|
+
timestamp: Date.now(),
|
|
1040
|
+
method: request3.method,
|
|
1041
|
+
path: request3.path,
|
|
1042
|
+
headers: request3.headers ?? {},
|
|
1043
|
+
...request3.body === void 0 ? {} : { body: request3.body }
|
|
1044
|
+
});
|
|
1045
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
|
|
1046
|
+
method: "POST",
|
|
1047
|
+
body,
|
|
1048
|
+
signal,
|
|
1049
|
+
headers: {
|
|
1050
|
+
"Content-Type": "application/json",
|
|
1051
|
+
"X-Prim-Proof": signature(
|
|
1052
|
+
environment.clientSecret,
|
|
1053
|
+
descriptor.nonce,
|
|
1054
|
+
body,
|
|
1055
|
+
FORWARD_REQUEST_PROOF
|
|
1056
|
+
)
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
|
|
1060
|
+
if (typeof envelope.body !== "string" || !matches(
|
|
1061
|
+
signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
|
|
1062
|
+
envelope.proof
|
|
1063
|
+
))
|
|
1064
|
+
throw new MachineAuthError(
|
|
1065
|
+
"broker_unavailable",
|
|
1066
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
1067
|
+
);
|
|
1068
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
1069
|
+
if (data.error) {
|
|
1070
|
+
const error = machineRecord(data.error);
|
|
1071
|
+
throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
|
|
1072
|
+
}
|
|
1073
|
+
const status = data.status;
|
|
1074
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
|
|
1075
|
+
throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
|
|
1076
|
+
const headers = new Headers();
|
|
1077
|
+
for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
|
|
1078
|
+
if (typeof value === "string") headers.set(name, value);
|
|
1079
|
+
const text = typeof data.body === "string" ? data.body : "";
|
|
1080
|
+
return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
|
|
1081
|
+
}
|
|
1082
|
+
async function forwardBrokerRequest(options) {
|
|
1083
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1084
|
+
const unavailable = () => new MachineAuthError(
|
|
1085
|
+
"broker_unavailable",
|
|
1086
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
1087
|
+
);
|
|
1088
|
+
const existing = readDescriptor(path);
|
|
1089
|
+
if (existing) {
|
|
1090
|
+
try {
|
|
1091
|
+
return await forwardOnce(existing, options.environment, options.request, options.signal);
|
|
1092
|
+
} catch (error) {
|
|
1093
|
+
options.signal.throwIfAborted();
|
|
1094
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1095
|
+
if (error.code !== "ECONNREFUSED") throw unavailable();
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
const descriptor = await ensureBroker(options);
|
|
900
1099
|
try {
|
|
901
|
-
return await
|
|
1100
|
+
return await forwardOnce(descriptor, options.environment, options.request, options.signal);
|
|
902
1101
|
} catch (error) {
|
|
903
1102
|
options.signal.throwIfAborted();
|
|
904
1103
|
if (error instanceof MachineAuthError) throw error;
|
|
905
|
-
throw
|
|
906
|
-
"broker_unavailable",
|
|
907
|
-
"Machine credential broker is unavailable. Retry the command."
|
|
908
|
-
);
|
|
1104
|
+
throw unavailable();
|
|
909
1105
|
}
|
|
910
1106
|
}
|
|
911
1107
|
|
|
912
1108
|
// src/lib/machine-retry.ts
|
|
913
1109
|
import { createHash as createHash2 } from "crypto";
|
|
914
|
-
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
1110
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
|
|
915
1111
|
import { join as join5 } from "path";
|
|
916
|
-
|
|
1112
|
+
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
1113
|
+
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
1114
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
917
1115
|
signal?.throwIfAborted();
|
|
918
1116
|
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
919
1117
|
const path = join5(directory, `machine_retry_${key}.json`);
|
|
920
|
-
let state = {
|
|
1118
|
+
let state = {
|
|
1119
|
+
failures: 0,
|
|
1120
|
+
retryAt: 0
|
|
1121
|
+
};
|
|
921
1122
|
try {
|
|
922
1123
|
const stat = lstatSync2(path);
|
|
923
1124
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
@@ -932,12 +1133,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
932
1133
|
if (state.retryAt > Date.now())
|
|
933
1134
|
throw new MachineAuthError(
|
|
934
1135
|
"token_service_unavailable",
|
|
935
|
-
"Machine authentication is cooling down after a temporary failure. Retry later."
|
|
1136
|
+
!isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
|
|
1137
|
+
// Cloud setup keeps this wait too, so pointing at it would loop.
|
|
1138
|
+
`${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
|
|
1139
|
+
) : (
|
|
1140
|
+
// The cooldown hides the failure that started it; cloud setup
|
|
1141
|
+
// retries at once and names the cause.
|
|
1142
|
+
cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
|
|
1143
|
+
),
|
|
936
1144
|
false,
|
|
937
1145
|
state.retryAt
|
|
938
1146
|
);
|
|
939
1147
|
try {
|
|
940
|
-
const result = await
|
|
1148
|
+
const result = await request3();
|
|
941
1149
|
rmSync4(path, { force: true });
|
|
942
1150
|
return result;
|
|
943
1151
|
} catch (error) {
|
|
@@ -949,8 +1157,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
949
1157
|
].includes(error.code)) {
|
|
950
1158
|
const failures = Math.min(16, state.failures + 1);
|
|
951
1159
|
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
952
|
-
const retryAt = error.retryAt
|
|
953
|
-
atomicWriteFile(
|
|
1160
|
+
const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
|
|
1161
|
+
atomicWriteFile(
|
|
1162
|
+
path,
|
|
1163
|
+
JSON.stringify({
|
|
1164
|
+
failures,
|
|
1165
|
+
retryAt,
|
|
1166
|
+
...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
|
|
1167
|
+
}),
|
|
1168
|
+
{ mode: 384 }
|
|
1169
|
+
);
|
|
954
1170
|
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
955
1171
|
}
|
|
956
1172
|
throw error;
|
|
@@ -1143,10 +1359,98 @@ function readMachineProfile(deps = {}) {
|
|
|
1143
1359
|
const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1144
1360
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1145
1361
|
}
|
|
1362
|
+
var NETWORK_SECRET_AUTH = "network-secret";
|
|
1363
|
+
var NETWORK_TOKEN_AUTH = "network-token";
|
|
1364
|
+
var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
1365
|
+
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1366
|
+
function networkSecretBrokerKey(deps, clientId) {
|
|
1367
|
+
const directory = configurationDirectory(deps);
|
|
1368
|
+
const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1369
|
+
const known = brokerKeys.get(path);
|
|
1370
|
+
if (known) return known;
|
|
1371
|
+
ensureDirectory(directory);
|
|
1372
|
+
const read = () => {
|
|
1373
|
+
try {
|
|
1374
|
+
const stat = lstatSync3(path);
|
|
1375
|
+
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1376
|
+
throw new MachineAuthError(
|
|
1377
|
+
"unsafe_storage",
|
|
1378
|
+
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1379
|
+
true
|
|
1380
|
+
);
|
|
1381
|
+
const value = readFileSync5(path, "utf8").trim();
|
|
1382
|
+
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1383
|
+
} catch (error) {
|
|
1384
|
+
if (error.code === "ENOENT") return void 0;
|
|
1385
|
+
throw error;
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1388
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1389
|
+
const existing = read();
|
|
1390
|
+
if (existing?.key) {
|
|
1391
|
+
brokerKeys.set(path, existing.key);
|
|
1392
|
+
return existing.key;
|
|
1393
|
+
}
|
|
1394
|
+
if (existing)
|
|
1395
|
+
throw new MachineAuthError(
|
|
1396
|
+
"unsafe_storage",
|
|
1397
|
+
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
1398
|
+
true
|
|
1399
|
+
);
|
|
1400
|
+
const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
|
|
1401
|
+
try {
|
|
1402
|
+
writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
|
|
1403
|
+
`, { mode: 384, flag: "wx" });
|
|
1404
|
+
protectPath(staged, false);
|
|
1405
|
+
linkSync(staged, path);
|
|
1406
|
+
} catch (error) {
|
|
1407
|
+
if (error.code !== "EEXIST") throw error;
|
|
1408
|
+
} finally {
|
|
1409
|
+
rmSync5(staged, { force: true });
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
const key = read()?.key;
|
|
1413
|
+
if (!key)
|
|
1414
|
+
throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
|
|
1415
|
+
brokerKeys.set(path, key);
|
|
1416
|
+
return key;
|
|
1417
|
+
}
|
|
1146
1418
|
function environmentCredentials(deps) {
|
|
1147
1419
|
const env = deps.env ?? process.env;
|
|
1148
|
-
const {
|
|
1149
|
-
|
|
1420
|
+
const {
|
|
1421
|
+
PRIM_M2M_CLIENT_ID: clientId,
|
|
1422
|
+
PRIM_M2M_CLIENT_SECRET: clientSecret,
|
|
1423
|
+
PRIM_M2M_CLIENT_AUTH: auth
|
|
1424
|
+
} = env;
|
|
1425
|
+
if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
|
|
1426
|
+
if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
|
|
1427
|
+
throw new MachineAuthError(
|
|
1428
|
+
"incomplete_machine_credentials",
|
|
1429
|
+
`PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
|
|
1430
|
+
);
|
|
1431
|
+
if (auth !== void 0) {
|
|
1432
|
+
if (!clientId || !/^client_[\w-]+$/u.test(clientId))
|
|
1433
|
+
throw new MachineAuthError(
|
|
1434
|
+
"incomplete_machine_credentials",
|
|
1435
|
+
`Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
|
|
1436
|
+
);
|
|
1437
|
+
if (clientSecret !== void 0)
|
|
1438
|
+
throw new MachineAuthError(
|
|
1439
|
+
"conflicting_credentials",
|
|
1440
|
+
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1441
|
+
);
|
|
1442
|
+
const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1443
|
+
const credentials = {
|
|
1444
|
+
clientId,
|
|
1445
|
+
generation,
|
|
1446
|
+
...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
|
|
1447
|
+
};
|
|
1448
|
+
Object.defineProperty(credentials, "clientSecret", {
|
|
1449
|
+
enumerable: true,
|
|
1450
|
+
get: () => networkSecretBrokerKey(deps, clientId)
|
|
1451
|
+
});
|
|
1452
|
+
return credentials;
|
|
1453
|
+
}
|
|
1150
1454
|
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1151
1455
|
throw new MachineAuthError(
|
|
1152
1456
|
"incomplete_machine_credentials",
|
|
@@ -1161,7 +1465,7 @@ function environmentCredentials(deps) {
|
|
|
1161
1465
|
}
|
|
1162
1466
|
function hasMachineConfiguration(deps = {}) {
|
|
1163
1467
|
const env = deps.env ?? process.env;
|
|
1164
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1468
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1165
1469
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1166
1470
|
throw new MachineAuthError(
|
|
1167
1471
|
"conflicting_credentials",
|
|
@@ -1198,6 +1502,8 @@ function machineSessionEnded(deps = {}) {
|
|
|
1198
1502
|
return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1199
1503
|
}
|
|
1200
1504
|
var environmentTerminal;
|
|
1505
|
+
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
1506
|
+
var networkRejection;
|
|
1201
1507
|
async function loadRecord(profile, deps, signal) {
|
|
1202
1508
|
const directory = configurationDirectory(deps);
|
|
1203
1509
|
let value;
|
|
@@ -1261,6 +1567,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1261
1567
|
const apiUrl = apiUrlFor(deps);
|
|
1262
1568
|
const environment = environmentCredentials(deps);
|
|
1263
1569
|
if (environment) {
|
|
1570
|
+
const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
|
|
1264
1571
|
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
1265
1572
|
const directory2 = configurationDirectory(deps);
|
|
1266
1573
|
ensureDirectory(directory2);
|
|
@@ -1278,7 +1585,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1278
1585
|
writeEnvironmentContext(cached, deps);
|
|
1279
1586
|
return cached;
|
|
1280
1587
|
} catch (error) {
|
|
1281
|
-
if (error instanceof MachineAuthError && error.terminal)
|
|
1588
|
+
if (error instanceof MachineAuthError && error.terminal && !networkManaged)
|
|
1282
1589
|
environmentTerminal = environment.generation;
|
|
1283
1590
|
throw error;
|
|
1284
1591
|
}
|
|
@@ -1289,11 +1596,13 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1289
1596
|
if (machineSessionEnded(deps))
|
|
1290
1597
|
throw new MachineAuthError(
|
|
1291
1598
|
"machine_credentials_rejected",
|
|
1292
|
-
"Rotate the injected machine credentials.",
|
|
1599
|
+
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1293
1600
|
true
|
|
1294
1601
|
);
|
|
1295
1602
|
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
|
|
1296
1603
|
return cached;
|
|
1604
|
+
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1605
|
+
throw networkRejection.error;
|
|
1297
1606
|
try {
|
|
1298
1607
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
1299
1608
|
directory2,
|
|
@@ -1302,13 +1611,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1302
1611
|
signal,
|
|
1303
1612
|
async () => {
|
|
1304
1613
|
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
1614
|
+
if (environment.tokenInjection) {
|
|
1615
|
+
const identity3 = await verifyInjectedMachineIdentity(
|
|
1616
|
+
apiUrl,
|
|
1617
|
+
environment.clientId,
|
|
1618
|
+
signal,
|
|
1619
|
+
deps.fetch
|
|
1620
|
+
);
|
|
1621
|
+
const tokens3 = {
|
|
1622
|
+
accessToken: "",
|
|
1623
|
+
expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
|
|
1624
|
+
};
|
|
1625
|
+
return { configuration: configuration2, tokens: tokens3, identity: identity3 };
|
|
1626
|
+
}
|
|
1305
1627
|
const tokens2 = await exchangeMachineCredentials(
|
|
1306
1628
|
configuration2,
|
|
1307
1629
|
environment.clientId,
|
|
1308
|
-
|
|
1630
|
+
// The broker key is not a client secret; the proxy supplies that.
|
|
1631
|
+
environment.secretInjection ? "" : environment.clientSecret,
|
|
1309
1632
|
signal,
|
|
1310
|
-
deps.fetch
|
|
1311
|
-
|
|
1633
|
+
deps.fetch,
|
|
1634
|
+
{ secretInjection: environment.secretInjection }
|
|
1635
|
+
).catch((error) => {
|
|
1636
|
+
if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
|
|
1637
|
+
throw new MachineAuthError(
|
|
1638
|
+
"network_secret_mismatch",
|
|
1639
|
+
`The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
|
|
1640
|
+
true
|
|
1641
|
+
);
|
|
1642
|
+
throw error;
|
|
1643
|
+
});
|
|
1312
1644
|
const identity2 = await verifyMachineIdentity(
|
|
1313
1645
|
apiUrl,
|
|
1314
1646
|
tokens2.accessToken,
|
|
@@ -1325,11 +1657,27 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1325
1657
|
...identity,
|
|
1326
1658
|
apiUrl,
|
|
1327
1659
|
generation: environment.generation,
|
|
1328
|
-
storage: "environment"
|
|
1660
|
+
storage: "environment",
|
|
1661
|
+
...environment.tokenInjection ? { tokenInjection: "network" } : {}
|
|
1329
1662
|
};
|
|
1330
1663
|
writeEnvironmentContext(cached, deps);
|
|
1331
1664
|
return cached;
|
|
1332
1665
|
} catch (error) {
|
|
1666
|
+
if (networkManaged && error instanceof MachineAuthError && error.terminal) {
|
|
1667
|
+
networkRejection = {
|
|
1668
|
+
generation: environment.generation,
|
|
1669
|
+
until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
|
|
1670
|
+
error
|
|
1671
|
+
};
|
|
1672
|
+
if (cached?.generation === environment.generation) cached = void 0;
|
|
1673
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1674
|
+
try {
|
|
1675
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1676
|
+
rmSync5(contextPath, { force: true });
|
|
1677
|
+
} catch {
|
|
1678
|
+
}
|
|
1679
|
+
throw error;
|
|
1680
|
+
}
|
|
1333
1681
|
if (error instanceof MachineAuthError && error.terminal) {
|
|
1334
1682
|
environmentTerminal = environment.generation;
|
|
1335
1683
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
@@ -1410,6 +1758,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1410
1758
|
{ signal }
|
|
1411
1759
|
);
|
|
1412
1760
|
}
|
|
1761
|
+
async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
1762
|
+
const environment = environmentCredentials(deps);
|
|
1763
|
+
if (!environment?.tokenInjection)
|
|
1764
|
+
throw new MachineAuthError(
|
|
1765
|
+
"identity_changed",
|
|
1766
|
+
"Machine identity changed; restart the operation."
|
|
1767
|
+
);
|
|
1768
|
+
const directory = configurationDirectory(deps);
|
|
1769
|
+
ensureDirectory(directory);
|
|
1770
|
+
return forwardBrokerRequest({
|
|
1771
|
+
directory,
|
|
1772
|
+
apiUrl: apiUrlFor(deps),
|
|
1773
|
+
environment,
|
|
1774
|
+
env: deps.env ?? process.env,
|
|
1775
|
+
request: request3,
|
|
1776
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1413
1779
|
|
|
1414
1780
|
// src/lib/credentials.ts
|
|
1415
1781
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
@@ -1435,7 +1801,7 @@ function readTrimmed(path) {
|
|
|
1435
1801
|
function resolveAuthCredential(options = {}) {
|
|
1436
1802
|
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
1437
1803
|
const machine = cachedMachineCredential({ env: options.env });
|
|
1438
|
-
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1804
|
+
return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1439
1805
|
}
|
|
1440
1806
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
1441
1807
|
if (envToken) return { token: envToken, source: "environment" };
|
|
@@ -1555,7 +1921,7 @@ function jwtExpiresAt(token) {
|
|
|
1555
1921
|
}
|
|
1556
1922
|
|
|
1557
1923
|
// src/daemon/client-instance-id.ts
|
|
1558
|
-
import { randomBytes as
|
|
1924
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1559
1925
|
import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
|
|
1560
1926
|
import { join as join8 } from "path";
|
|
1561
1927
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
@@ -1618,7 +1984,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
1618
1984
|
if (existing !== void 0) {
|
|
1619
1985
|
return existing;
|
|
1620
1986
|
}
|
|
1621
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
1987
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
|
|
1622
1988
|
"base64url"
|
|
1623
1989
|
)}`;
|
|
1624
1990
|
if (!isClientInstanceId(generated)) {
|
|
@@ -1700,6 +2066,9 @@ var CREDENTIAL_FILE_MODE = 384;
|
|
|
1700
2066
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
1701
2067
|
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1702
2068
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
2069
|
+
function authExpiredMessage() {
|
|
2070
|
+
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
2071
|
+
}
|
|
1703
2072
|
function readTrimmed2(path) {
|
|
1704
2073
|
try {
|
|
1705
2074
|
const value = readFileSync8(path, "utf8").trim();
|
|
@@ -2081,7 +2450,7 @@ var CliManagementResponseError = class extends Error {
|
|
|
2081
2450
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
2082
2451
|
async function managementResponseValue(response) {
|
|
2083
2452
|
if (response.status === 401) {
|
|
2084
|
-
throw new HttpError(401,
|
|
2453
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2085
2454
|
}
|
|
2086
2455
|
let value;
|
|
2087
2456
|
try {
|
|
@@ -2103,23 +2472,50 @@ function selectedCredential() {
|
|
|
2103
2472
|
}
|
|
2104
2473
|
return _cachedCredential;
|
|
2105
2474
|
}
|
|
2475
|
+
async function requestHeaders(method, path) {
|
|
2476
|
+
return {
|
|
2477
|
+
"Content-Type": "application/json",
|
|
2478
|
+
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2106
2481
|
async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
2107
2482
|
return fetch(`${siteUrl}${path}`, {
|
|
2108
2483
|
method,
|
|
2109
|
-
headers: {
|
|
2110
|
-
Authorization: `Bearer ${token}`,
|
|
2111
|
-
"Content-Type": "application/json",
|
|
2112
|
-
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
2113
|
-
},
|
|
2484
|
+
headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
|
|
2114
2485
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
2115
2486
|
signal: options?.signal,
|
|
2116
2487
|
redirect: options?.redirect
|
|
2117
2488
|
});
|
|
2118
2489
|
}
|
|
2490
|
+
async function fetchAsMachine(credential, method, path, body, options) {
|
|
2491
|
+
if (!credential.tokenInjection)
|
|
2492
|
+
return fetchWithToken(
|
|
2493
|
+
method,
|
|
2494
|
+
path,
|
|
2495
|
+
body,
|
|
2496
|
+
{ ...options, redirect: "error" },
|
|
2497
|
+
credential.accessToken,
|
|
2498
|
+
credential.apiUrl
|
|
2499
|
+
);
|
|
2500
|
+
try {
|
|
2501
|
+
return await forwardMachineRequest(
|
|
2502
|
+
{
|
|
2503
|
+
method,
|
|
2504
|
+
path,
|
|
2505
|
+
headers: await requestHeaders(method, path),
|
|
2506
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
2507
|
+
},
|
|
2508
|
+
options.signal
|
|
2509
|
+
);
|
|
2510
|
+
} catch (error) {
|
|
2511
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
2512
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2119
2515
|
async function responseValue(response) {
|
|
2120
2516
|
if (!response.ok) {
|
|
2121
2517
|
if (response.status === 401) {
|
|
2122
|
-
throw new HttpError(401,
|
|
2518
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2123
2519
|
}
|
|
2124
2520
|
const errorBody = await response.json().catch(() => null);
|
|
2125
2521
|
const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
|
|
@@ -2146,14 +2542,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2146
2542
|
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
2147
2543
|
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
2148
2544
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2149
|
-
let response = await
|
|
2150
|
-
method,
|
|
2151
|
-
path,
|
|
2152
|
-
body,
|
|
2153
|
-
{ ...requestOptions, redirect: "error" },
|
|
2154
|
-
current.accessToken,
|
|
2155
|
-
selected.apiUrl
|
|
2156
|
-
);
|
|
2545
|
+
let response = await fetchAsMachine(current, method, path, body, requestOptions);
|
|
2157
2546
|
if (response.status === 401) {
|
|
2158
2547
|
const renewed = await acquireMachineCredential({
|
|
2159
2548
|
force: true,
|
|
@@ -2162,19 +2551,14 @@ async function machineClient(options = {}, management = false) {
|
|
|
2162
2551
|
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
2163
2552
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2164
2553
|
}
|
|
2165
|
-
response = await
|
|
2166
|
-
method,
|
|
2167
|
-
path,
|
|
2168
|
-
body,
|
|
2169
|
-
{ ...requestOptions, redirect: "error" },
|
|
2170
|
-
renewed.accessToken,
|
|
2171
|
-
renewed.apiUrl
|
|
2172
|
-
);
|
|
2554
|
+
response = await fetchAsMachine(renewed, method, path, body, requestOptions);
|
|
2173
2555
|
}
|
|
2174
2556
|
if (response.status === 401)
|
|
2175
2557
|
throw new HttpError(
|
|
2176
2558
|
401,
|
|
2177
|
-
"Machine access was rejected.
|
|
2559
|
+
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(
|
|
2560
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2561
|
+
)
|
|
2178
2562
|
);
|
|
2179
2563
|
return parse(response);
|
|
2180
2564
|
};
|
|
@@ -2184,7 +2568,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2184
2568
|
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
2185
2569
|
};
|
|
2186
2570
|
}
|
|
2187
|
-
async function
|
|
2571
|
+
async function request2(method, path, body, options) {
|
|
2188
2572
|
const machine = await machineClient(options);
|
|
2189
2573
|
if (machine)
|
|
2190
2574
|
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
@@ -2200,10 +2584,10 @@ async function request(method, path, body, options) {
|
|
|
2200
2584
|
if (token) credential = { token, source: "token_file" };
|
|
2201
2585
|
}
|
|
2202
2586
|
if (!credential) {
|
|
2203
|
-
throw new HttpError(401,
|
|
2587
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2204
2588
|
}
|
|
2205
2589
|
if (isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
2206
|
-
throw new HttpError(401,
|
|
2590
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2207
2591
|
}
|
|
2208
2592
|
const tokenUsed = credential.token;
|
|
2209
2593
|
let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
|
|
@@ -2226,8 +2610,8 @@ async function request(method, path, body, options) {
|
|
|
2226
2610
|
}
|
|
2227
2611
|
function getClient() {
|
|
2228
2612
|
return {
|
|
2229
|
-
get: (path, options) =>
|
|
2230
|
-
post: (path, body, options) =>
|
|
2613
|
+
get: (path, options) => request2("GET", path, void 0, options),
|
|
2614
|
+
post: (path, body, options) => request2("POST", path, body, options)
|
|
2231
2615
|
};
|
|
2232
2616
|
}
|
|
2233
2617
|
|
|
@@ -2296,7 +2680,7 @@ var nextRequestId = 1;
|
|
|
2296
2680
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
2297
2681
|
const id = nextRequestId++;
|
|
2298
2682
|
const caller = resolveDaemonPrincipal();
|
|
2299
|
-
const
|
|
2683
|
+
const request3 = {
|
|
2300
2684
|
id,
|
|
2301
2685
|
method,
|
|
2302
2686
|
params,
|
|
@@ -2335,7 +2719,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
2335
2719
|
});
|
|
2336
2720
|
socket.on("connect", () => {
|
|
2337
2721
|
try {
|
|
2338
|
-
socket?.write(`${JSON.stringify(
|
|
2722
|
+
socket?.write(`${JSON.stringify(request3)}
|
|
2339
2723
|
`);
|
|
2340
2724
|
} catch {
|
|
2341
2725
|
clearTimeout(timer);
|
|
@@ -2405,8 +2789,12 @@ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_T
|
|
|
2405
2789
|
|
|
2406
2790
|
// src/lib/activation.ts
|
|
2407
2791
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
2408
|
-
import { existsSync as
|
|
2792
|
+
import { existsSync as existsSync6, readFileSync as readFileSync11 } from "fs";
|
|
2409
2793
|
import { homedir as homedir2 } from "os";
|
|
2794
|
+
import { join as join13 } from "path";
|
|
2795
|
+
|
|
2796
|
+
// src/lib/cloud-prepared.ts
|
|
2797
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync9, rmSync as rmSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
2410
2798
|
import { join as join11 } from "path";
|
|
2411
2799
|
|
|
2412
2800
|
// src/lib/demo-pause.ts
|
|
@@ -2416,11 +2804,12 @@ var DEMO_PAUSE_MS = 30 * 6e4;
|
|
|
2416
2804
|
// src/lib/git.ts
|
|
2417
2805
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
2418
2806
|
import { createHash as createHash7 } from "crypto";
|
|
2419
|
-
import { lstatSync as lstatSync5, realpathSync } from "fs";
|
|
2420
|
-
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
|
|
2807
|
+
import { lstatSync as lstatSync5, readFileSync as readFileSync10, realpathSync } from "fs";
|
|
2808
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, join as join12, relative, resolve as resolve2, sep } from "path";
|
|
2421
2809
|
var GIT_TIMEOUT_MS = 1e3;
|
|
2810
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
2422
2811
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
2423
|
-
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
2812
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
2424
2813
|
function gitToplevel(cwd) {
|
|
2425
2814
|
try {
|
|
2426
2815
|
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
@@ -2449,19 +2838,57 @@ function gitValue(cwd, args) {
|
|
|
2449
2838
|
function currentBranch(cwd) {
|
|
2450
2839
|
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
2451
2840
|
}
|
|
2452
|
-
function
|
|
2453
|
-
const
|
|
2454
|
-
if (
|
|
2841
|
+
function parseGithubRepositoryName(path) {
|
|
2842
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
2843
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
2844
|
+
return null;
|
|
2845
|
+
}
|
|
2846
|
+
return `${parts[0]}/${parts[1]}`;
|
|
2847
|
+
}
|
|
2848
|
+
function githubRepositoryFromRemote(remote) {
|
|
2849
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
2455
2850
|
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
2456
2851
|
remote
|
|
2457
2852
|
);
|
|
2458
2853
|
const path = match?.[1] ?? match?.[2];
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2854
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
2855
|
+
}
|
|
2856
|
+
function checkoutSettingsText(repoRoot) {
|
|
2857
|
+
const path = join12(repoRoot, ".claude", "settings.json");
|
|
2858
|
+
try {
|
|
2859
|
+
if (!lstatSync5(join12(repoRoot, ".claude")).isDirectory()) return null;
|
|
2860
|
+
const stat = lstatSync5(path);
|
|
2861
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
2862
|
+
return readFileSync10(path, "utf8");
|
|
2863
|
+
} catch {
|
|
2462
2864
|
return null;
|
|
2463
2865
|
}
|
|
2464
|
-
|
|
2866
|
+
}
|
|
2867
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
2868
|
+
const text = checkoutSettingsText(repoRoot);
|
|
2869
|
+
if (text === null) return null;
|
|
2870
|
+
let parsed;
|
|
2871
|
+
try {
|
|
2872
|
+
parsed = JSON.parse(text);
|
|
2873
|
+
} catch {
|
|
2874
|
+
return null;
|
|
2875
|
+
}
|
|
2876
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
2877
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
2878
|
+
return typeof value === "string" ? value : null;
|
|
2879
|
+
}
|
|
2880
|
+
function declaredGithubRepository(repoRoot) {
|
|
2881
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
2882
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
2883
|
+
}
|
|
2884
|
+
function githubRepositoryFullName(cwd) {
|
|
2885
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
2886
|
+
if (remote) {
|
|
2887
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
2888
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
2889
|
+
}
|
|
2890
|
+
const root = gitToplevel(cwd);
|
|
2891
|
+
return root ? declaredGithubRepository(root) : null;
|
|
2465
2892
|
}
|
|
2466
2893
|
function canonicalGitRoot(cwd) {
|
|
2467
2894
|
try {
|
|
@@ -2471,6 +2898,27 @@ function canonicalGitRoot(cwd) {
|
|
|
2471
2898
|
return null;
|
|
2472
2899
|
}
|
|
2473
2900
|
}
|
|
2901
|
+
function normalizeOriginRemote(remote) {
|
|
2902
|
+
const value = remote.trim();
|
|
2903
|
+
if (!value) return void 0;
|
|
2904
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
2905
|
+
if (scp?.host && scp.path) {
|
|
2906
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
2907
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
2908
|
+
}
|
|
2909
|
+
try {
|
|
2910
|
+
const url = new URL(value);
|
|
2911
|
+
url.username = "";
|
|
2912
|
+
url.password = "";
|
|
2913
|
+
url.search = "";
|
|
2914
|
+
url.hash = "";
|
|
2915
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
2916
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
2917
|
+
return void 0;
|
|
2918
|
+
} catch {
|
|
2919
|
+
return void 0;
|
|
2920
|
+
}
|
|
2921
|
+
}
|
|
2474
2922
|
function nearestExistingAncestor(path) {
|
|
2475
2923
|
const suffix = [];
|
|
2476
2924
|
let cursor = path;
|
|
@@ -2623,7 +3071,7 @@ async function checkAffectedDecisions(filePaths, deps = defaultDeps) {
|
|
|
2623
3071
|
return {
|
|
2624
3072
|
decisions: [],
|
|
2625
3073
|
truncated: false,
|
|
2626
|
-
unavailable: "this checkout has no current Primitive repository binding; run prim enable"
|
|
3074
|
+
unavailable: isClaudeCloudSession() ? cloudSetupPointer("this checkout has no current Primitive repository binding") : "this checkout has no current Primitive repository binding; run prim enable"
|
|
2627
3075
|
};
|
|
2628
3076
|
}
|
|
2629
3077
|
const canonical = filePaths.map(
|