@primitive.ai/prim 0.1.0-alpha.126 → 0.1.0-alpha.128
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +211 -1
- package/SKILL.md +6 -1
- package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
- package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
- package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
- package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
- package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
- package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
- package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
- package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
- package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
- package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
- package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
- package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
- package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
- package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
- package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
- package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
- package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
- package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
- package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
- package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
- package/dist/daemon/server.js +1976 -442
- package/dist/hook-runtime/daemon/server.js +1976 -442
- package/dist/hook-runtime/hooks/post-commit.js +592 -212
- package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
- package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
- package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
- package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
- package/dist/hook-runtime/hooks/session-end.js +549 -180
- package/dist/hook-runtime/hooks/session-start.js +2213 -596
- package/dist/hook-runtime/index.js +5318 -2423
- package/dist/hook-runtime/statusline-main.js +531 -150
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +18 -18
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +14 -15
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +95 -21
- package/dist/index.js +1386 -299
- package/dist/statusline-main.js +531 -150
- package/package.json +1 -1
|
@@ -53,25 +53,34 @@ var require_ucs2length = __commonJS({
|
|
|
53
53
|
});
|
|
54
54
|
|
|
55
55
|
// src/hooks/post-tool-use.ts
|
|
56
|
-
import { readFileSync as
|
|
57
|
-
import { dirname as dirname14, join as
|
|
56
|
+
import { readFileSync as readFileSync22 } from "fs";
|
|
57
|
+
import { dirname as dirname14, join as join27 } from "path";
|
|
58
58
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
59
59
|
|
|
60
60
|
// src/binding.ts
|
|
61
|
-
import { existsSync as existsSync4, readFileSync as
|
|
62
|
-
import { dirname as
|
|
61
|
+
import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
|
|
62
|
+
import { dirname as dirname6, join as join10 } from "path";
|
|
63
63
|
|
|
64
64
|
// src/lib/credentials.ts
|
|
65
|
-
import { createHash as
|
|
66
|
-
import { readFileSync as
|
|
67
|
-
import { join as
|
|
65
|
+
import { createHash as createHash6 } from "crypto";
|
|
66
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
67
|
+
import { join as join9 } from "path";
|
|
68
68
|
|
|
69
69
|
// src/lib/machine-credentials.ts
|
|
70
|
-
import { execFileSync } from "child_process";
|
|
71
|
-
import { createHash as
|
|
72
|
-
import {
|
|
70
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
71
|
+
import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
|
|
72
|
+
import {
|
|
73
|
+
chmodSync,
|
|
74
|
+
existsSync as existsSync3,
|
|
75
|
+
linkSync,
|
|
76
|
+
lstatSync as lstatSync4,
|
|
77
|
+
mkdirSync as mkdirSync3,
|
|
78
|
+
readFileSync as readFileSync6,
|
|
79
|
+
rmSync as rmSync6,
|
|
80
|
+
writeFileSync as writeFileSync3
|
|
81
|
+
} from "fs";
|
|
73
82
|
import { createRequire } from "module";
|
|
74
|
-
import { dirname as
|
|
83
|
+
import { dirname as dirname5, join as join8 } from "path";
|
|
75
84
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
76
85
|
|
|
77
86
|
// src/lib/atomic-file.ts
|
|
@@ -388,6 +397,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
|
388
397
|
'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
|
|
389
398
|
"fi; fi; "
|
|
390
399
|
].join("");
|
|
400
|
+
var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
|
|
391
401
|
function stableHookCommand(bin, args = "") {
|
|
392
402
|
if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
|
|
393
403
|
throw new Error("invalid stable hook command");
|
|
@@ -399,7 +409,7 @@ function stableHookCommand(bin, args = "") {
|
|
|
399
409
|
`prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
|
|
400
410
|
PRIM_CONFIG_SHELL_RESOLVER,
|
|
401
411
|
`case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
|
|
402
|
-
|
|
412
|
+
LAUNCHER_EXEC
|
|
403
413
|
].join("");
|
|
404
414
|
const suffix = args ? ` ${args}` : "";
|
|
405
415
|
return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
|
|
@@ -408,6 +418,49 @@ function detachedHookShimCommand(bin, args = "") {
|
|
|
408
418
|
return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
|
|
409
419
|
}
|
|
410
420
|
|
|
421
|
+
// src/lib/loopback-fetch.ts
|
|
422
|
+
import { request } from "http";
|
|
423
|
+
import { Readable } from "stream";
|
|
424
|
+
function loopbackFetch(url, init = {}) {
|
|
425
|
+
const target = new URL(url);
|
|
426
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
427
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
428
|
+
return new Promise((resolve8, reject) => {
|
|
429
|
+
const outgoing = request(
|
|
430
|
+
target,
|
|
431
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
432
|
+
(incoming) => {
|
|
433
|
+
try {
|
|
434
|
+
const headers = new Headers();
|
|
435
|
+
for (const [name2, value] of Object.entries(incoming.headers))
|
|
436
|
+
if (typeof value === "string") headers.set(name2, value);
|
|
437
|
+
const status = incoming.statusCode ?? 502;
|
|
438
|
+
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
439
|
+
resolve8(new Response(body, { status, headers }));
|
|
440
|
+
} catch (error) {
|
|
441
|
+
incoming.destroy();
|
|
442
|
+
reject(error);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
);
|
|
446
|
+
outgoing.once("error", reject);
|
|
447
|
+
outgoing.end(init.body);
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/lib/cloud-env.ts
|
|
452
|
+
function isClaudeCloudSession(env = process.env) {
|
|
453
|
+
return env.CLAUDE_CODE_REMOTE === "true";
|
|
454
|
+
}
|
|
455
|
+
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';
|
|
456
|
+
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';
|
|
457
|
+
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}.`;
|
|
458
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
459
|
+
function cloudSetupPointer(message, env = process.env) {
|
|
460
|
+
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
461
|
+
}
|
|
462
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
463
|
+
|
|
411
464
|
// src/lib/workos-connect.ts
|
|
412
465
|
var TOKEN_PATH = "/oauth2/token";
|
|
413
466
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -544,10 +597,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
544
597
|
"access_token",
|
|
545
598
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
546
599
|
);
|
|
547
|
-
const
|
|
600
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
548
601
|
return {
|
|
549
602
|
accessToken,
|
|
550
|
-
refreshToken:
|
|
603
|
+
refreshToken: refreshToken3,
|
|
551
604
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
552
605
|
};
|
|
553
606
|
}
|
|
@@ -603,9 +656,19 @@ function parseMachineConfiguration(value) {
|
|
|
603
656
|
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
604
657
|
};
|
|
605
658
|
}
|
|
659
|
+
function rejectedCredentialsMessage(message, env = process.env) {
|
|
660
|
+
return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
661
|
+
}
|
|
606
662
|
function machineSignal(signal) {
|
|
607
663
|
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
608
664
|
}
|
|
665
|
+
function hostOf(url) {
|
|
666
|
+
try {
|
|
667
|
+
return new URL(url).hostname;
|
|
668
|
+
} catch {
|
|
669
|
+
return "Primitive";
|
|
670
|
+
}
|
|
671
|
+
}
|
|
609
672
|
async function fetchMachine(url, options, fetchImpl) {
|
|
610
673
|
try {
|
|
611
674
|
return await fetchImpl(url, options);
|
|
@@ -613,7 +676,9 @@ async function fetchMachine(url, options, fetchImpl) {
|
|
|
613
676
|
options.signal?.throwIfAborted();
|
|
614
677
|
throw new MachineAuthError(
|
|
615
678
|
"authentication_unavailable",
|
|
616
|
-
|
|
679
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
680
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
681
|
+
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."
|
|
617
682
|
);
|
|
618
683
|
}
|
|
619
684
|
}
|
|
@@ -640,8 +705,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
|
640
705
|
);
|
|
641
706
|
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
642
707
|
}
|
|
643
|
-
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
644
|
-
|
|
708
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
709
|
+
const network = options.secretInjection === "network";
|
|
710
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
645
711
|
throw new MachineAuthError(
|
|
646
712
|
"invalid_credentials",
|
|
647
713
|
"A machine client ID and secret are required.",
|
|
@@ -655,11 +721,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
655
721
|
redirect: "error",
|
|
656
722
|
signal: machineSignal(signal),
|
|
657
723
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
client_secret: clientSecret
|
|
662
|
-
|
|
724
|
+
// With a network secret the agent proxy authenticates the client with
|
|
725
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
726
|
+
body: new URLSearchParams(
|
|
727
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
728
|
+
)
|
|
663
729
|
},
|
|
664
730
|
fetchImpl
|
|
665
731
|
);
|
|
@@ -667,7 +733,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
667
733
|
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
668
734
|
throw new MachineAuthError(
|
|
669
735
|
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
670
|
-
terminal ?
|
|
736
|
+
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(
|
|
737
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
738
|
+
) : "The machine token service is temporarily unavailable.",
|
|
671
739
|
terminal,
|
|
672
740
|
terminal ? void 0 : machineRetryAt(response)
|
|
673
741
|
);
|
|
@@ -687,6 +755,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
687
755
|
} catch {
|
|
688
756
|
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
689
757
|
}
|
|
758
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
759
|
+
throw new MachineAuthError(
|
|
760
|
+
"token_client_mismatch",
|
|
761
|
+
"The token service issued a token for another machine client."
|
|
762
|
+
);
|
|
690
763
|
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()) {
|
|
691
764
|
throw new MachineAuthError(
|
|
692
765
|
"token_identity_mismatch",
|
|
@@ -732,12 +805,51 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
|
|
|
732
805
|
const terminal = response.status === 401 || response.status === 403;
|
|
733
806
|
throw new MachineAuthError(
|
|
734
807
|
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
735
|
-
terminal ?
|
|
808
|
+
terminal ? rejectedCredentialsMessage(
|
|
809
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
810
|
+
) : "Machine verification is temporarily unavailable.",
|
|
736
811
|
terminal
|
|
737
812
|
);
|
|
738
813
|
}
|
|
739
814
|
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
740
815
|
}
|
|
816
|
+
function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
|
|
817
|
+
const rejected = () => new MachineAuthError(
|
|
818
|
+
"network_token_rejected",
|
|
819
|
+
`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.`,
|
|
820
|
+
true
|
|
821
|
+
);
|
|
822
|
+
if (status === 401 || status === 403) throw rejected();
|
|
823
|
+
if (status < 200 || status > 299)
|
|
824
|
+
throw new MachineAuthError(
|
|
825
|
+
"verification_unavailable",
|
|
826
|
+
"Machine verification is temporarily unavailable."
|
|
827
|
+
);
|
|
828
|
+
let data;
|
|
829
|
+
try {
|
|
830
|
+
data = machineRecord(value);
|
|
831
|
+
} catch {
|
|
832
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
833
|
+
}
|
|
834
|
+
if (data.authenticated !== true) throw rejected();
|
|
835
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
836
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
837
|
+
throw new MachineAuthError(
|
|
838
|
+
"network_secret_mismatch",
|
|
839
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
840
|
+
true
|
|
841
|
+
);
|
|
842
|
+
return parseMachineIdentity(data, clientId);
|
|
843
|
+
}
|
|
844
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
845
|
+
const response = await fetchMachine(
|
|
846
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
847
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
848
|
+
fetchImpl
|
|
849
|
+
);
|
|
850
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
851
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
852
|
+
}
|
|
741
853
|
|
|
742
854
|
// src/lib/paths.ts
|
|
743
855
|
import { homedir } from "os";
|
|
@@ -769,6 +881,11 @@ function primConfigDirectory(options = {}) {
|
|
|
769
881
|
|
|
770
882
|
// src/lib/machine-broker.ts
|
|
771
883
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
884
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
885
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
886
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
887
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
888
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
772
889
|
var IDLE_MS = 5 * 6e4;
|
|
773
890
|
function descriptorPath(directory, generation) {
|
|
774
891
|
return join4(directory, `machine_broker_${generation}.json`);
|
|
@@ -784,8 +901,8 @@ function readDescriptor(path) {
|
|
|
784
901
|
return void 0;
|
|
785
902
|
}
|
|
786
903
|
}
|
|
787
|
-
function signature(secret, nonce, body) {
|
|
788
|
-
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
904
|
+
function signature(secret, nonce, body, purpose) {
|
|
905
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
789
906
|
}
|
|
790
907
|
function matches(left, right) {
|
|
791
908
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
@@ -800,10 +917,9 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
800
917
|
observedTokenHash: tokenHash(options.observedToken),
|
|
801
918
|
timestamp: Date.now()
|
|
802
919
|
});
|
|
803
|
-
const response = await
|
|
920
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
804
921
|
method: "POST",
|
|
805
922
|
body,
|
|
806
|
-
redirect: "error",
|
|
807
923
|
signal: options.signal,
|
|
808
924
|
headers: {
|
|
809
925
|
"Content-Type": "application/json",
|
|
@@ -834,6 +950,15 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
834
950
|
);
|
|
835
951
|
return credential;
|
|
836
952
|
}
|
|
953
|
+
function brokerEnvironment(options) {
|
|
954
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
955
|
+
return {
|
|
956
|
+
...options.env,
|
|
957
|
+
PRIM_API_URL: options.apiUrl,
|
|
958
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
959
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
960
|
+
};
|
|
961
|
+
}
|
|
837
962
|
async function acquireBrokerCredential(options) {
|
|
838
963
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
839
964
|
const existing = readDescriptor(path);
|
|
@@ -845,15 +970,28 @@ async function acquireBrokerCredential(options) {
|
|
|
845
970
|
if (error instanceof MachineAuthError) throw error;
|
|
846
971
|
}
|
|
847
972
|
}
|
|
848
|
-
const descriptor = await
|
|
973
|
+
const descriptor = await ensureBroker(options);
|
|
974
|
+
try {
|
|
975
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
976
|
+
} catch (error) {
|
|
977
|
+
options.signal.throwIfAborted();
|
|
978
|
+
if (error instanceof MachineAuthError) throw error;
|
|
979
|
+
throw new MachineAuthError(
|
|
980
|
+
"broker_unavailable",
|
|
981
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
982
|
+
);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
async function ensureBroker(options) {
|
|
986
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
987
|
+
return withFileLock(
|
|
849
988
|
join4(options.directory, "machine-broker.lock"),
|
|
850
989
|
async () => {
|
|
851
990
|
const current = readDescriptor(path);
|
|
852
991
|
if (current) {
|
|
853
992
|
try {
|
|
854
|
-
const response = await
|
|
855
|
-
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
856
|
-
redirect: "error"
|
|
993
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
994
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
857
995
|
});
|
|
858
996
|
if (response.ok && await response.text() === current.nonce) return current;
|
|
859
997
|
} catch {
|
|
@@ -872,7 +1010,7 @@ async function acquireBrokerCredential(options) {
|
|
|
872
1010
|
detached: true,
|
|
873
1011
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
874
1012
|
windowsHide: true,
|
|
875
|
-
env:
|
|
1013
|
+
env: brokerEnvironment(options)
|
|
876
1014
|
});
|
|
877
1015
|
let settled = false;
|
|
878
1016
|
const finish2 = (error) => {
|
|
@@ -924,27 +1062,93 @@ async function acquireBrokerCredential(options) {
|
|
|
924
1062
|
},
|
|
925
1063
|
{ signal: options.signal }
|
|
926
1064
|
);
|
|
1065
|
+
}
|
|
1066
|
+
async function forwardOnce(descriptor, environment, request3, signal) {
|
|
1067
|
+
const body = JSON.stringify({
|
|
1068
|
+
generation: environment.generation,
|
|
1069
|
+
timestamp: Date.now(),
|
|
1070
|
+
method: request3.method,
|
|
1071
|
+
path: request3.path,
|
|
1072
|
+
headers: request3.headers ?? {},
|
|
1073
|
+
...request3.body === void 0 ? {} : { body: request3.body }
|
|
1074
|
+
});
|
|
1075
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
|
|
1076
|
+
method: "POST",
|
|
1077
|
+
body,
|
|
1078
|
+
signal,
|
|
1079
|
+
headers: {
|
|
1080
|
+
"Content-Type": "application/json",
|
|
1081
|
+
"X-Prim-Proof": signature(
|
|
1082
|
+
environment.clientSecret,
|
|
1083
|
+
descriptor.nonce,
|
|
1084
|
+
body,
|
|
1085
|
+
FORWARD_REQUEST_PROOF
|
|
1086
|
+
)
|
|
1087
|
+
}
|
|
1088
|
+
});
|
|
1089
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
|
|
1090
|
+
if (typeof envelope.body !== "string" || !matches(
|
|
1091
|
+
signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
|
|
1092
|
+
envelope.proof
|
|
1093
|
+
))
|
|
1094
|
+
throw new MachineAuthError(
|
|
1095
|
+
"broker_unavailable",
|
|
1096
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
1097
|
+
);
|
|
1098
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
1099
|
+
if (data.error) {
|
|
1100
|
+
const error = machineRecord(data.error);
|
|
1101
|
+
throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
|
|
1102
|
+
}
|
|
1103
|
+
const status = data.status;
|
|
1104
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
|
|
1105
|
+
throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
|
|
1106
|
+
const headers = new Headers();
|
|
1107
|
+
for (const [name2, value] of Object.entries(machineRecord(data.headers ?? {})))
|
|
1108
|
+
if (typeof value === "string") headers.set(name2, value);
|
|
1109
|
+
const text = typeof data.body === "string" ? data.body : "";
|
|
1110
|
+
return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
|
|
1111
|
+
}
|
|
1112
|
+
async function forwardBrokerRequest(options) {
|
|
1113
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1114
|
+
const unavailable = () => new MachineAuthError(
|
|
1115
|
+
"broker_unavailable",
|
|
1116
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
1117
|
+
);
|
|
1118
|
+
const existing = readDescriptor(path);
|
|
1119
|
+
if (existing) {
|
|
1120
|
+
try {
|
|
1121
|
+
return await forwardOnce(existing, options.environment, options.request, options.signal);
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
options.signal.throwIfAborted();
|
|
1124
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1125
|
+
if (error.code !== "ECONNREFUSED") throw unavailable();
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
const descriptor = await ensureBroker(options);
|
|
927
1129
|
try {
|
|
928
|
-
return await
|
|
1130
|
+
return await forwardOnce(descriptor, options.environment, options.request, options.signal);
|
|
929
1131
|
} catch (error) {
|
|
930
1132
|
options.signal.throwIfAborted();
|
|
931
1133
|
if (error instanceof MachineAuthError) throw error;
|
|
932
|
-
throw
|
|
933
|
-
"broker_unavailable",
|
|
934
|
-
"Machine credential broker is unavailable. Retry the command."
|
|
935
|
-
);
|
|
1134
|
+
throw unavailable();
|
|
936
1135
|
}
|
|
937
1136
|
}
|
|
938
1137
|
|
|
939
1138
|
// src/lib/machine-retry.ts
|
|
940
1139
|
import { createHash as createHash2 } from "crypto";
|
|
941
|
-
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
1140
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
|
|
942
1141
|
import { join as join5 } from "path";
|
|
943
|
-
|
|
1142
|
+
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
1143
|
+
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
1144
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
944
1145
|
signal?.throwIfAborted();
|
|
945
1146
|
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
946
1147
|
const path = join5(directory, `machine_retry_${key}.json`);
|
|
947
|
-
let state = {
|
|
1148
|
+
let state = {
|
|
1149
|
+
failures: 0,
|
|
1150
|
+
retryAt: 0
|
|
1151
|
+
};
|
|
948
1152
|
try {
|
|
949
1153
|
const stat = lstatSync2(path);
|
|
950
1154
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
@@ -959,12 +1163,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
959
1163
|
if (state.retryAt > Date.now())
|
|
960
1164
|
throw new MachineAuthError(
|
|
961
1165
|
"token_service_unavailable",
|
|
962
|
-
"Machine authentication is cooling down after a temporary failure. Retry later."
|
|
1166
|
+
!isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
|
|
1167
|
+
// Cloud setup keeps this wait too, so pointing at it would loop.
|
|
1168
|
+
`${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
|
|
1169
|
+
) : (
|
|
1170
|
+
// The cooldown hides the failure that started it; cloud setup
|
|
1171
|
+
// retries at once and names the cause.
|
|
1172
|
+
cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
|
|
1173
|
+
),
|
|
963
1174
|
false,
|
|
964
1175
|
state.retryAt
|
|
965
1176
|
);
|
|
966
1177
|
try {
|
|
967
|
-
const result = await
|
|
1178
|
+
const result = await request3();
|
|
968
1179
|
rmSync4(path, { force: true });
|
|
969
1180
|
return result;
|
|
970
1181
|
} catch (error) {
|
|
@@ -976,40 +1187,1280 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
976
1187
|
].includes(error.code)) {
|
|
977
1188
|
const failures = Math.min(16, state.failures + 1);
|
|
978
1189
|
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
979
|
-
const retryAt = error.retryAt
|
|
980
|
-
atomicWriteFile(
|
|
1190
|
+
const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
|
|
1191
|
+
atomicWriteFile(
|
|
1192
|
+
path,
|
|
1193
|
+
JSON.stringify({
|
|
1194
|
+
failures,
|
|
1195
|
+
retryAt,
|
|
1196
|
+
...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
|
|
1197
|
+
}),
|
|
1198
|
+
{ mode: 384 }
|
|
1199
|
+
);
|
|
981
1200
|
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
982
1201
|
}
|
|
983
1202
|
throw error;
|
|
984
1203
|
}
|
|
985
1204
|
}
|
|
986
1205
|
|
|
1206
|
+
// src/lib/session-identity.ts
|
|
1207
|
+
import { execFile } from "child_process";
|
|
1208
|
+
import { createHash as createHash4 } from "crypto";
|
|
1209
|
+
import { rmSync as rmSync5 } from "fs";
|
|
1210
|
+
import { join as join7 } from "path";
|
|
1211
|
+
import { promisify } from "util";
|
|
1212
|
+
|
|
1213
|
+
// src/lib/git.ts
|
|
1214
|
+
import { execFileSync } from "child_process";
|
|
1215
|
+
import { createHash as createHash3 } from "crypto";
|
|
1216
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
|
|
1217
|
+
import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
|
|
1218
|
+
var GIT_TIMEOUT_MS = 1e3;
|
|
1219
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
1220
|
+
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
1221
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
1222
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
1223
|
+
function gitChildEnvironment(env = process.env) {
|
|
1224
|
+
return Object.fromEntries(
|
|
1225
|
+
Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
function gitToplevel(cwd) {
|
|
1229
|
+
try {
|
|
1230
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1231
|
+
cwd,
|
|
1232
|
+
encoding: "utf-8",
|
|
1233
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1234
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1235
|
+
env: gitChildEnvironment()
|
|
1236
|
+
}).trim();
|
|
1237
|
+
} catch {
|
|
1238
|
+
return null;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
function gitValue(cwd, args) {
|
|
1242
|
+
try {
|
|
1243
|
+
const value = execFileSync("git", args, {
|
|
1244
|
+
cwd,
|
|
1245
|
+
encoding: "utf-8",
|
|
1246
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1247
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1248
|
+
env: gitChildEnvironment()
|
|
1249
|
+
}).trim();
|
|
1250
|
+
return value || void 0;
|
|
1251
|
+
} catch {
|
|
1252
|
+
return void 0;
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
function currentBranch(cwd) {
|
|
1256
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
1257
|
+
}
|
|
1258
|
+
function parseGithubRepositoryName(path) {
|
|
1259
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
1260
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
1261
|
+
return null;
|
|
1262
|
+
}
|
|
1263
|
+
return `${parts[0]}/${parts[1]}`;
|
|
1264
|
+
}
|
|
1265
|
+
function githubRepositoryFromRemote(remote) {
|
|
1266
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
1267
|
+
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
1268
|
+
remote
|
|
1269
|
+
);
|
|
1270
|
+
const path = match?.[1] ?? match?.[2];
|
|
1271
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
1272
|
+
}
|
|
1273
|
+
function checkoutSettingsText(repoRoot) {
|
|
1274
|
+
const path = join6(repoRoot, ".claude", "settings.json");
|
|
1275
|
+
try {
|
|
1276
|
+
if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
|
|
1277
|
+
const stat = lstatSync3(path);
|
|
1278
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
1279
|
+
return readFileSync5(path, "utf8");
|
|
1280
|
+
} catch {
|
|
1281
|
+
return null;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
function checkoutDeclaration(repoRoot, name2) {
|
|
1285
|
+
const text = checkoutSettingsText(repoRoot);
|
|
1286
|
+
if (text === null) return null;
|
|
1287
|
+
let parsed;
|
|
1288
|
+
try {
|
|
1289
|
+
parsed = JSON.parse(text);
|
|
1290
|
+
} catch {
|
|
1291
|
+
return null;
|
|
1292
|
+
}
|
|
1293
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
1294
|
+
const value = typeof env === "object" && env !== null ? env[name2] : void 0;
|
|
1295
|
+
return typeof value === "string" ? value : null;
|
|
1296
|
+
}
|
|
1297
|
+
function declaredGithubRepository(repoRoot) {
|
|
1298
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
1299
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
1300
|
+
}
|
|
1301
|
+
function githubRepositoryFullName(cwd) {
|
|
1302
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
1303
|
+
if (remote) {
|
|
1304
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
1305
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
1306
|
+
}
|
|
1307
|
+
const root = gitToplevel(cwd);
|
|
1308
|
+
return root ? declaredGithubRepository(root) : null;
|
|
1309
|
+
}
|
|
1310
|
+
function canonicalGitRoot(cwd) {
|
|
1311
|
+
try {
|
|
1312
|
+
const top = gitToplevel(cwd);
|
|
1313
|
+
return top ? realpathSync.native(top) : null;
|
|
1314
|
+
} catch {
|
|
1315
|
+
return null;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
function relatedWorktreeTarget(path, cwd, origin) {
|
|
1319
|
+
let parent = dirname4(resolve(cwd, path));
|
|
1320
|
+
while (true) {
|
|
1321
|
+
try {
|
|
1322
|
+
realpathSync.native(parent);
|
|
1323
|
+
break;
|
|
1324
|
+
} catch {
|
|
1325
|
+
const next = dirname4(parent);
|
|
1326
|
+
if (next === parent) return null;
|
|
1327
|
+
parent = next;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
const target = resolveRepositoryContext(parent);
|
|
1331
|
+
if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
|
|
1332
|
+
const common = (root) => {
|
|
1333
|
+
const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
|
|
1334
|
+
try {
|
|
1335
|
+
return value ? realpathSync.native(resolve(root, value)) : void 0;
|
|
1336
|
+
} catch {
|
|
1337
|
+
return void 0;
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
const originCommon = common(origin.repoRoot);
|
|
1341
|
+
return originCommon && originCommon === common(target.repoRoot) ? target : null;
|
|
1342
|
+
}
|
|
1343
|
+
function normalizeOriginRemote(remote) {
|
|
1344
|
+
const value = remote.trim();
|
|
1345
|
+
if (!value) return void 0;
|
|
1346
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
1347
|
+
if (scp?.host && scp.path) {
|
|
1348
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1349
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
1350
|
+
}
|
|
1351
|
+
try {
|
|
1352
|
+
const url = new URL(value);
|
|
1353
|
+
url.username = "";
|
|
1354
|
+
url.password = "";
|
|
1355
|
+
url.search = "";
|
|
1356
|
+
url.hash = "";
|
|
1357
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1358
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
1359
|
+
return void 0;
|
|
1360
|
+
} catch {
|
|
1361
|
+
return void 0;
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
function opaqueRepoKey(source, value) {
|
|
1365
|
+
return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
|
|
1366
|
+
}
|
|
1367
|
+
function resolveRepositoryContext(cwd = process.cwd()) {
|
|
1368
|
+
const top = gitToplevel(cwd);
|
|
1369
|
+
if (!top) return null;
|
|
1370
|
+
let repoRoot;
|
|
1371
|
+
try {
|
|
1372
|
+
repoRoot = realpathSync.native(top);
|
|
1373
|
+
} catch {
|
|
1374
|
+
repoRoot = resolve(top);
|
|
1375
|
+
}
|
|
1376
|
+
const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
|
|
1377
|
+
const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
|
|
1378
|
+
const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
|
|
1379
|
+
if (normalizedOrigin) {
|
|
1380
|
+
return {
|
|
1381
|
+
repoRoot,
|
|
1382
|
+
repoKey: opaqueRepoKey("origin", normalizedOrigin),
|
|
1383
|
+
identitySource: "origin",
|
|
1384
|
+
repoFullName
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
if (repoFullName) {
|
|
1388
|
+
return {
|
|
1389
|
+
repoRoot,
|
|
1390
|
+
repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
|
|
1391
|
+
identitySource: "declared",
|
|
1392
|
+
repoFullName
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
1396
|
+
if (roots && roots.length > 0) {
|
|
1397
|
+
return {
|
|
1398
|
+
repoRoot,
|
|
1399
|
+
repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
|
|
1400
|
+
identitySource: "root_commit",
|
|
1401
|
+
repoFullName
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
return { repoRoot, repoFullName };
|
|
1405
|
+
}
|
|
1406
|
+
function nearestExistingAncestor(path) {
|
|
1407
|
+
const suffix = [];
|
|
1408
|
+
let cursor = path;
|
|
1409
|
+
while (true) {
|
|
1410
|
+
try {
|
|
1411
|
+
lstatSync3(cursor);
|
|
1412
|
+
break;
|
|
1413
|
+
} catch (error) {
|
|
1414
|
+
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
1415
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
1416
|
+
const parent = dirname4(cursor);
|
|
1417
|
+
if (parent === cursor) return null;
|
|
1418
|
+
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
1419
|
+
cursor = parent;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
try {
|
|
1423
|
+
return { real: realpathSync.native(cursor), suffix };
|
|
1424
|
+
} catch {
|
|
1425
|
+
return null;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
1429
|
+
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
1430
|
+
return { ok: false, reason: "invalid_path" };
|
|
1431
|
+
}
|
|
1432
|
+
const absolute = resolve(baseDir, filePath);
|
|
1433
|
+
const resolved = nearestExistingAncestor(absolute);
|
|
1434
|
+
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
1435
|
+
const target = resolve(resolved.real, ...resolved.suffix);
|
|
1436
|
+
const rel = relative(context.repoRoot, target);
|
|
1437
|
+
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
1438
|
+
if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1439
|
+
return { ok: false, reason: "outside_repository" };
|
|
1440
|
+
}
|
|
1441
|
+
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
1442
|
+
}
|
|
1443
|
+
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
1444
|
+
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
1445
|
+
return null;
|
|
1446
|
+
const absolute = resolve(cwd, filePath);
|
|
1447
|
+
let target;
|
|
1448
|
+
try {
|
|
1449
|
+
const stat = lstatSync3(absolute);
|
|
1450
|
+
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
1451
|
+
target = realpathSync.native(absolute);
|
|
1452
|
+
} catch (error) {
|
|
1453
|
+
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
1454
|
+
return null;
|
|
1455
|
+
}
|
|
1456
|
+
try {
|
|
1457
|
+
const parent = realpathSync.native(dirname4(absolute));
|
|
1458
|
+
if (!lstatSync3(parent).isDirectory()) return null;
|
|
1459
|
+
target = resolve(parent, basename2(absolute));
|
|
1460
|
+
} catch {
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
const rel = relative(repositoryRoot, target);
|
|
1465
|
+
if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1466
|
+
return null;
|
|
1467
|
+
}
|
|
1468
|
+
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
1469
|
+
}
|
|
1470
|
+
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
1471
|
+
if (typeof contextOrCwd === "string") {
|
|
1472
|
+
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
1473
|
+
}
|
|
1474
|
+
return canonicalRepositoryPathScoped(
|
|
1475
|
+
filePath,
|
|
1476
|
+
contextOrCwd,
|
|
1477
|
+
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
1478
|
+
);
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
// src/lib/terminal-safe.ts
|
|
1482
|
+
function replaceIsolatedSurrogates(value) {
|
|
1483
|
+
let out = "";
|
|
1484
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1485
|
+
const unit = value.charCodeAt(index);
|
|
1486
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
1487
|
+
const next = value.charCodeAt(index + 1);
|
|
1488
|
+
if (next >= 56320 && next <= 57343) {
|
|
1489
|
+
out += value[index] + value[index + 1];
|
|
1490
|
+
index += 1;
|
|
1491
|
+
} else {
|
|
1492
|
+
out += "\uFFFD";
|
|
1493
|
+
}
|
|
1494
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
1495
|
+
out += "\uFFFD";
|
|
1496
|
+
} else {
|
|
1497
|
+
out += value[index];
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
return out;
|
|
1501
|
+
}
|
|
1502
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
1503
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
1504
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
1505
|
+
point === 1564 || // Arabic letter mark
|
|
1506
|
+
point === 6158 || // Mongolian vowel separator
|
|
1507
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
1508
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
1509
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
1510
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
1511
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
1512
|
+
point >= 917504 && point <= 917631;
|
|
1513
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
1514
|
+
}
|
|
1515
|
+
function terminalSafeText(value) {
|
|
1516
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
1517
|
+
}
|
|
1518
|
+
function terminalSafeLine(value) {
|
|
1519
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
1520
|
+
}
|
|
1521
|
+
var stripControlChars = terminalSafeText;
|
|
1522
|
+
|
|
1523
|
+
// src/lib/session-identity.ts
|
|
1524
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
1525
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
1526
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
1527
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
1528
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
1529
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
1530
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
1531
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
1532
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
1533
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
1534
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
1535
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
1536
|
+
token: "/api/cli/session-identity/token",
|
|
1537
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
1538
|
+
link: "/api/cli/session-identity/link"
|
|
1539
|
+
};
|
|
1540
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
1541
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
1542
|
+
var GIT_TIMEOUT_MS2 = 1e4;
|
|
1543
|
+
var POLL_BUDGET_MS = 15e3;
|
|
1544
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
1545
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
1546
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
1547
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
1548
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
1549
|
+
function sessionIdentityRequested(env = process.env) {
|
|
1550
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
1551
|
+
}
|
|
1552
|
+
function sessionIdentityMode(deps = {}) {
|
|
1553
|
+
const env = deps.env ?? process.env;
|
|
1554
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
1555
|
+
}
|
|
1556
|
+
function failure(code, cause, remedy) {
|
|
1557
|
+
return { status: "failed", code, cause, remedy };
|
|
1558
|
+
}
|
|
1559
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
1560
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
1561
|
+
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';
|
|
1562
|
+
var SESSION_REVOKED = failure(
|
|
1563
|
+
"session_revoked",
|
|
1564
|
+
"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",
|
|
1565
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
1566
|
+
);
|
|
1567
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
1568
|
+
"challenge_expired",
|
|
1569
|
+
"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)",
|
|
1570
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
1571
|
+
);
|
|
1572
|
+
var CHALLENGE_GONE = failure(
|
|
1573
|
+
"challenge_not_found",
|
|
1574
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
1575
|
+
NEW_SESSION_REMEDY
|
|
1576
|
+
);
|
|
1577
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
1578
|
+
function rejectionFailure(reason, repository) {
|
|
1579
|
+
switch (reason) {
|
|
1580
|
+
case "identity_mismatch":
|
|
1581
|
+
return failure(
|
|
1582
|
+
"identity_mismatch",
|
|
1583
|
+
"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",
|
|
1584
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
1585
|
+
);
|
|
1586
|
+
case "push_after_expiry":
|
|
1587
|
+
return failure(
|
|
1588
|
+
"push_after_expiry",
|
|
1589
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
1590
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
1591
|
+
);
|
|
1592
|
+
case "repository_mismatch":
|
|
1593
|
+
return failure(
|
|
1594
|
+
"repository_mismatch",
|
|
1595
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
1596
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
1597
|
+
);
|
|
1598
|
+
case "conflicting_push":
|
|
1599
|
+
return failure(
|
|
1600
|
+
"conflicting_push",
|
|
1601
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
1602
|
+
NEW_SESSION_REMEDY
|
|
1603
|
+
);
|
|
1604
|
+
case "unsupported_sender":
|
|
1605
|
+
return failure(
|
|
1606
|
+
"unsupported_sender",
|
|
1607
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
1608
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
1609
|
+
);
|
|
1610
|
+
default:
|
|
1611
|
+
return failure(
|
|
1612
|
+
"challenge_rejected",
|
|
1613
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
1614
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
1615
|
+
);
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
function sessionIdentityMessage(outcome) {
|
|
1619
|
+
if (outcome.status === "link_required")
|
|
1620
|
+
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.`;
|
|
1621
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1622
|
+
}
|
|
1623
|
+
function hash(value) {
|
|
1624
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
1625
|
+
}
|
|
1626
|
+
function sessionContext(deps) {
|
|
1627
|
+
const env = deps.env ?? process.env;
|
|
1628
|
+
const environment = environmentCredentials(deps);
|
|
1629
|
+
if (!environment)
|
|
1630
|
+
return failure(
|
|
1631
|
+
"environment_credential_missing",
|
|
1632
|
+
"the cloud environment has no environment credential",
|
|
1633
|
+
'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'
|
|
1634
|
+
);
|
|
1635
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
1636
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
1637
|
+
return failure(
|
|
1638
|
+
"session_id_missing",
|
|
1639
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
1640
|
+
NEW_SESSION_REMEDY
|
|
1641
|
+
);
|
|
1642
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
1643
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
1644
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
1645
|
+
return {
|
|
1646
|
+
directory,
|
|
1647
|
+
apiUrl,
|
|
1648
|
+
clientId: environment.clientId,
|
|
1649
|
+
generation: environment.generation,
|
|
1650
|
+
sessionId,
|
|
1651
|
+
tokenPath: join7(directory, `session_identity_${key}.json`),
|
|
1652
|
+
statePath: join7(directory, `session_identity_${key}.state.json`),
|
|
1653
|
+
lockPath: join7(directory, "session-identity.lock")
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
function readRecord(path) {
|
|
1657
|
+
try {
|
|
1658
|
+
const value = readMachineMetadata(path);
|
|
1659
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
1660
|
+
} catch {
|
|
1661
|
+
return void 0;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
function finiteNumber(value) {
|
|
1665
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1666
|
+
}
|
|
1667
|
+
function readToken(context) {
|
|
1668
|
+
const data = readRecord(context.tokenPath);
|
|
1669
|
+
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))
|
|
1670
|
+
return void 0;
|
|
1671
|
+
const identity = data.identity;
|
|
1672
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
1673
|
+
return void 0;
|
|
1674
|
+
return data;
|
|
1675
|
+
}
|
|
1676
|
+
function readState(context) {
|
|
1677
|
+
const data = readRecord(context.statePath);
|
|
1678
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
1679
|
+
return void 0;
|
|
1680
|
+
return data;
|
|
1681
|
+
}
|
|
1682
|
+
function writeToken(context, record) {
|
|
1683
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1684
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
1685
|
+
rmSync5(context.statePath, { force: true });
|
|
1686
|
+
}
|
|
1687
|
+
function writeState(context, state) {
|
|
1688
|
+
try {
|
|
1689
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1690
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
1691
|
+
} catch {
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
function tokenValid(record, now = Date.now()) {
|
|
1695
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
1696
|
+
}
|
|
1697
|
+
function tokenFresh(record, now = Date.now()) {
|
|
1698
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
1699
|
+
}
|
|
1700
|
+
function toCredential(record) {
|
|
1701
|
+
return {
|
|
1702
|
+
issuer: record.issuer,
|
|
1703
|
+
audience: record.audience,
|
|
1704
|
+
...record.identity,
|
|
1705
|
+
accessToken: record.accessToken,
|
|
1706
|
+
expiresAt: record.expiresAt,
|
|
1707
|
+
apiUrl: record.apiUrl,
|
|
1708
|
+
generation: record.generation,
|
|
1709
|
+
storage: "environment",
|
|
1710
|
+
session: {
|
|
1711
|
+
userId: record.userId,
|
|
1712
|
+
displayName: record.displayName,
|
|
1713
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1714
|
+
refreshAfter: record.refreshAfter
|
|
1715
|
+
}
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
function identified(record, reused) {
|
|
1719
|
+
return {
|
|
1720
|
+
status: "ok",
|
|
1721
|
+
credential: toCredential(record),
|
|
1722
|
+
displayName: record.displayName,
|
|
1723
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1724
|
+
reused
|
|
1725
|
+
};
|
|
1726
|
+
}
|
|
1727
|
+
function cachedSessionCredential(deps = {}) {
|
|
1728
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
1729
|
+
let context;
|
|
1730
|
+
try {
|
|
1731
|
+
context = sessionContext(deps);
|
|
1732
|
+
} catch {
|
|
1733
|
+
return void 0;
|
|
1734
|
+
}
|
|
1735
|
+
if ("status" in context) return void 0;
|
|
1736
|
+
const record = readToken(context);
|
|
1737
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
1738
|
+
}
|
|
1739
|
+
function outcomeFromState(state) {
|
|
1740
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
1741
|
+
return {
|
|
1742
|
+
status: "link_required",
|
|
1743
|
+
githubLogin: state.githubLogin,
|
|
1744
|
+
challengeId: state.challengeId,
|
|
1745
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
1746
|
+
};
|
|
1747
|
+
return failure(
|
|
1748
|
+
state.code,
|
|
1749
|
+
state.cause ?? "the last identity check failed",
|
|
1750
|
+
state.remedy ?? RETRY_REMEDY
|
|
1751
|
+
);
|
|
1752
|
+
}
|
|
1753
|
+
function parseInstant(value) {
|
|
1754
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
1755
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
1756
|
+
const parsed = Date.parse(value);
|
|
1757
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1758
|
+
}
|
|
1759
|
+
return void 0;
|
|
1760
|
+
}
|
|
1761
|
+
async function sendJson(url, init, fetchImpl) {
|
|
1762
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
1763
|
+
let value;
|
|
1764
|
+
try {
|
|
1765
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
1766
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
1767
|
+
} catch {
|
|
1768
|
+
value = void 0;
|
|
1769
|
+
}
|
|
1770
|
+
return { status: response.status, value };
|
|
1771
|
+
}
|
|
1772
|
+
function environmentOnly(deps) {
|
|
1773
|
+
return { ...deps, environmentOnly: true };
|
|
1774
|
+
}
|
|
1775
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
1776
|
+
const send = async (credential2) => {
|
|
1777
|
+
const headers = { "Content-Type": "application/json" };
|
|
1778
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
1779
|
+
if (credential2.tokenInjection) {
|
|
1780
|
+
const response = await forwardMachineRequest(
|
|
1781
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
1782
|
+
signal,
|
|
1783
|
+
environmentOnly(deps)
|
|
1784
|
+
);
|
|
1785
|
+
const parsed = await response.json().catch(() => void 0);
|
|
1786
|
+
return {
|
|
1787
|
+
status: response.status,
|
|
1788
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
return sendJson(
|
|
1792
|
+
`${credential2.apiUrl}${path}`,
|
|
1793
|
+
{
|
|
1794
|
+
method,
|
|
1795
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
1796
|
+
...text === void 0 ? {} : { body: text },
|
|
1797
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
|
|
1798
|
+
},
|
|
1799
|
+
deps.fetch ?? fetch
|
|
1800
|
+
);
|
|
1801
|
+
};
|
|
1802
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1803
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1804
|
+
let answer = await send(credential);
|
|
1805
|
+
if (answer.status === 401) {
|
|
1806
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
1807
|
+
if (!credential)
|
|
1808
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1809
|
+
answer = await send(credential);
|
|
1810
|
+
}
|
|
1811
|
+
return answer;
|
|
1812
|
+
}
|
|
1813
|
+
function environmentFailure(error, apiUrl) {
|
|
1814
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1815
|
+
return failure(
|
|
1816
|
+
"environment_credential_rejected",
|
|
1817
|
+
"Primitive rejected the cloud environment's credential",
|
|
1818
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
1819
|
+
);
|
|
1820
|
+
const host = (() => {
|
|
1821
|
+
try {
|
|
1822
|
+
return new URL(apiUrl).hostname;
|
|
1823
|
+
} catch {
|
|
1824
|
+
return "Primitive";
|
|
1825
|
+
}
|
|
1826
|
+
})();
|
|
1827
|
+
return failure(
|
|
1828
|
+
"identity_unavailable",
|
|
1829
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
1830
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
1831
|
+
);
|
|
1832
|
+
}
|
|
1833
|
+
function answerError(answer) {
|
|
1834
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
1835
|
+
}
|
|
1836
|
+
async function git(root, args, signal) {
|
|
1837
|
+
try {
|
|
1838
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
1839
|
+
cwd: root,
|
|
1840
|
+
encoding: "utf8",
|
|
1841
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
1842
|
+
signal,
|
|
1843
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
1844
|
+
maxBuffer: 1024 * 1024
|
|
1845
|
+
});
|
|
1846
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
1847
|
+
} catch (error) {
|
|
1848
|
+
const failed = error;
|
|
1849
|
+
return {
|
|
1850
|
+
ok: false,
|
|
1851
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
1852
|
+
stdout: failed.stdout ?? "",
|
|
1853
|
+
stderr: failed.stderr ?? "",
|
|
1854
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
1855
|
+
};
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
function gitDetail(stderr) {
|
|
1859
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
1860
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
1861
|
+
}
|
|
1862
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
1863
|
+
await new Promise((resolve8, reject) => {
|
|
1864
|
+
const timer = setTimeout(resolve8, milliseconds);
|
|
1865
|
+
signal?.addEventListener(
|
|
1866
|
+
"abort",
|
|
1867
|
+
() => {
|
|
1868
|
+
clearTimeout(timer);
|
|
1869
|
+
reject(signal.reason);
|
|
1870
|
+
},
|
|
1871
|
+
{ once: true }
|
|
1872
|
+
);
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
1876
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
1877
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
1878
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
1879
|
+
let unreachable;
|
|
1880
|
+
for (; ; ) {
|
|
1881
|
+
const remaining = deadline - Date.now();
|
|
1882
|
+
if (remaining <= 0) break;
|
|
1883
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
1884
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
1885
|
+
let answer;
|
|
1886
|
+
try {
|
|
1887
|
+
answer = await environmentRequest(
|
|
1888
|
+
"GET",
|
|
1889
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
1890
|
+
void 0,
|
|
1891
|
+
deps,
|
|
1892
|
+
signal
|
|
1893
|
+
);
|
|
1894
|
+
} catch (error) {
|
|
1895
|
+
signal?.throwIfAborted();
|
|
1896
|
+
unreachable = error;
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
1900
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1901
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
1902
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
1903
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
1904
|
+
continue;
|
|
1905
|
+
}
|
|
1906
|
+
unreachable = void 0;
|
|
1907
|
+
const status = answer.value;
|
|
1908
|
+
if (status?.status === "verified")
|
|
1909
|
+
return {
|
|
1910
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
1911
|
+
};
|
|
1912
|
+
if (status?.status === "expired")
|
|
1913
|
+
return failure(
|
|
1914
|
+
"challenge_expired",
|
|
1915
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
1916
|
+
NEW_SESSION_REMEDY
|
|
1917
|
+
);
|
|
1918
|
+
if (status?.status === "rejected")
|
|
1919
|
+
return rejectionFailure(status.reason, repository);
|
|
1920
|
+
}
|
|
1921
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
1922
|
+
return failure(
|
|
1923
|
+
"webhook_timeout",
|
|
1924
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
1925
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
1926
|
+
);
|
|
1927
|
+
}
|
|
1928
|
+
function parseTokenAnswer(value) {
|
|
1929
|
+
if (!value) return void 0;
|
|
1930
|
+
const user = value.user;
|
|
1931
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
1932
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
1933
|
+
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))
|
|
1934
|
+
return void 0;
|
|
1935
|
+
return {
|
|
1936
|
+
accessToken: value.accessToken,
|
|
1937
|
+
expiresAt,
|
|
1938
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
1939
|
+
userId: user.id,
|
|
1940
|
+
displayName: user.displayName,
|
|
1941
|
+
organizationId: value.organizationId
|
|
1942
|
+
};
|
|
1943
|
+
}
|
|
1944
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
1945
|
+
"server_contract",
|
|
1946
|
+
"Primitive's answer did not identify the linked member",
|
|
1947
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
1948
|
+
);
|
|
1949
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
1950
|
+
let identity;
|
|
1951
|
+
let environment;
|
|
1952
|
+
try {
|
|
1953
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1954
|
+
identity = await verifyMachineIdentity(
|
|
1955
|
+
context.apiUrl,
|
|
1956
|
+
answer.accessToken,
|
|
1957
|
+
context.clientId,
|
|
1958
|
+
signal,
|
|
1959
|
+
deps.fetch
|
|
1960
|
+
);
|
|
1961
|
+
} catch (error) {
|
|
1962
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
1963
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1964
|
+
return environmentFailure(error, context.apiUrl);
|
|
1965
|
+
}
|
|
1966
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
1967
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1968
|
+
return {
|
|
1969
|
+
version: 1,
|
|
1970
|
+
apiUrl: context.apiUrl,
|
|
1971
|
+
clientId: context.clientId,
|
|
1972
|
+
generation: context.generation,
|
|
1973
|
+
sessionId: context.sessionId,
|
|
1974
|
+
issuer: environment.issuer,
|
|
1975
|
+
audience: environment.audience,
|
|
1976
|
+
accessToken: answer.accessToken,
|
|
1977
|
+
expiresAt: answer.expiresAt,
|
|
1978
|
+
refreshAfter: answer.refreshAfter,
|
|
1979
|
+
userId: answer.userId,
|
|
1980
|
+
displayName: answer.displayName,
|
|
1981
|
+
organizationId: answer.organizationId,
|
|
1982
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
1983
|
+
identity,
|
|
1984
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
async function refreshToken(context, record, deps, signal) {
|
|
1988
|
+
let answer;
|
|
1989
|
+
try {
|
|
1990
|
+
answer = await environmentRequest(
|
|
1991
|
+
"POST",
|
|
1992
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
1993
|
+
{ accessToken: record.accessToken },
|
|
1994
|
+
deps,
|
|
1995
|
+
signal
|
|
1996
|
+
);
|
|
1997
|
+
} catch (error) {
|
|
1998
|
+
signal?.throwIfAborted();
|
|
1999
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
2000
|
+
}
|
|
2001
|
+
const code = answerError(answer);
|
|
2002
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
2003
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
2004
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2005
|
+
return {
|
|
2006
|
+
status: "refused",
|
|
2007
|
+
failure: environmentFailure(
|
|
2008
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
2009
|
+
context.apiUrl
|
|
2010
|
+
)
|
|
2011
|
+
};
|
|
2012
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2013
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
2014
|
+
return { status: "unavailable" };
|
|
2015
|
+
return {
|
|
2016
|
+
status: "ok",
|
|
2017
|
+
record: {
|
|
2018
|
+
...record,
|
|
2019
|
+
accessToken: token.accessToken,
|
|
2020
|
+
expiresAt: token.expiresAt,
|
|
2021
|
+
refreshAfter: token.refreshAfter,
|
|
2022
|
+
displayName: token.displayName
|
|
2023
|
+
}
|
|
2024
|
+
};
|
|
2025
|
+
}
|
|
2026
|
+
function exchangeRefusal(answer, repository) {
|
|
2027
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2028
|
+
if (answer.status !== 409) return void 0;
|
|
2029
|
+
switch (answerError(answer)) {
|
|
2030
|
+
case "identity_mismatch":
|
|
2031
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
2032
|
+
case "challenge_rejected":
|
|
2033
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
2034
|
+
case "challenge_expired":
|
|
2035
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
2036
|
+
case "challenge_already_exchanged":
|
|
2037
|
+
return failure(
|
|
2038
|
+
"challenge_already_exchanged",
|
|
2039
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
2040
|
+
NEW_SESSION_REMEDY
|
|
2041
|
+
);
|
|
2042
|
+
case "challenge_pending":
|
|
2043
|
+
return failure(
|
|
2044
|
+
"webhook_timeout",
|
|
2045
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
2046
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2047
|
+
);
|
|
2048
|
+
default:
|
|
2049
|
+
return void 0;
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
2053
|
+
let answer;
|
|
2054
|
+
try {
|
|
2055
|
+
answer = await environmentRequest(
|
|
2056
|
+
"POST",
|
|
2057
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
2058
|
+
{ challengeId: challenge.challengeId },
|
|
2059
|
+
deps,
|
|
2060
|
+
signal
|
|
2061
|
+
);
|
|
2062
|
+
} catch (error) {
|
|
2063
|
+
signal?.throwIfAborted();
|
|
2064
|
+
return environmentFailure(error, context.apiUrl);
|
|
2065
|
+
}
|
|
2066
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
2067
|
+
const login = answer.value?.githubLogin;
|
|
2068
|
+
return {
|
|
2069
|
+
status: "link_required",
|
|
2070
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
2071
|
+
challengeId: challenge.challengeId,
|
|
2072
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
2073
|
+
};
|
|
2074
|
+
}
|
|
2075
|
+
const refused = exchangeRefusal(
|
|
2076
|
+
answer,
|
|
2077
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
2078
|
+
);
|
|
2079
|
+
if (refused) return refused;
|
|
2080
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2081
|
+
if (!token) {
|
|
2082
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2083
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2084
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2085
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2086
|
+
context.apiUrl
|
|
2087
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2088
|
+
}
|
|
2089
|
+
return recordFor(
|
|
2090
|
+
context,
|
|
2091
|
+
token,
|
|
2092
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
2093
|
+
deps,
|
|
2094
|
+
signal
|
|
2095
|
+
);
|
|
2096
|
+
}
|
|
2097
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
2098
|
+
const env = deps.env ?? process.env;
|
|
2099
|
+
const repository = githubRepositoryFullName(root);
|
|
2100
|
+
if (!repository)
|
|
2101
|
+
return failure(
|
|
2102
|
+
"repository_unidentified",
|
|
2103
|
+
"this checkout does not name its GitHub repository",
|
|
2104
|
+
"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"
|
|
2105
|
+
);
|
|
2106
|
+
const branch = currentBranch(root);
|
|
2107
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
2108
|
+
return failure(
|
|
2109
|
+
"not_session_branch",
|
|
2110
|
+
`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`,
|
|
2111
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
2112
|
+
);
|
|
2113
|
+
attempt.branch = branch;
|
|
2114
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
2115
|
+
if (!baseSha) {
|
|
2116
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
2117
|
+
baseSha = head.stdout.trim();
|
|
2118
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
2119
|
+
return failure(
|
|
2120
|
+
"no_commit",
|
|
2121
|
+
"this checkout has no commit to create the session branch at",
|
|
2122
|
+
NEW_SESSION_REMEDY
|
|
2123
|
+
);
|
|
2124
|
+
}
|
|
2125
|
+
const published = await git(
|
|
2126
|
+
root,
|
|
2127
|
+
[
|
|
2128
|
+
"for-each-ref",
|
|
2129
|
+
"--count=1",
|
|
2130
|
+
"--format=%(refname)",
|
|
2131
|
+
"--contains",
|
|
2132
|
+
baseSha,
|
|
2133
|
+
"refs/remotes/origin/"
|
|
2134
|
+
],
|
|
2135
|
+
signal
|
|
2136
|
+
);
|
|
2137
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
2138
|
+
return failure(
|
|
2139
|
+
"unpublished_commits",
|
|
2140
|
+
`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`,
|
|
2141
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
2142
|
+
);
|
|
2143
|
+
attempt.baseSha = baseSha;
|
|
2144
|
+
const remote = await git(
|
|
2145
|
+
root,
|
|
2146
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
2147
|
+
signal
|
|
2148
|
+
);
|
|
2149
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
2150
|
+
if (remote.ok && recorded) {
|
|
2151
|
+
Object.assign(attempt, recorded);
|
|
2152
|
+
return { ...recorded, repository };
|
|
2153
|
+
}
|
|
2154
|
+
if (remote.ok)
|
|
2155
|
+
return failure(
|
|
2156
|
+
"branch_exists",
|
|
2157
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
2158
|
+
NEW_SESSION_REMEDY
|
|
2159
|
+
);
|
|
2160
|
+
if (remote.code !== 2)
|
|
2161
|
+
return failure(
|
|
2162
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
2163
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
2164
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
2165
|
+
);
|
|
2166
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
2167
|
+
Object.assign(attempt, recorded);
|
|
2168
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
2169
|
+
}
|
|
2170
|
+
let answer;
|
|
2171
|
+
try {
|
|
2172
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
2173
|
+
answer = await environmentRequest(
|
|
2174
|
+
"POST",
|
|
2175
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
2176
|
+
{
|
|
2177
|
+
repositoryFullName: repository,
|
|
2178
|
+
claudeSessionId: context.sessionId,
|
|
2179
|
+
branch,
|
|
2180
|
+
baseSha,
|
|
2181
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
2182
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
2183
|
+
},
|
|
2184
|
+
deps,
|
|
2185
|
+
signal
|
|
2186
|
+
);
|
|
2187
|
+
} catch (error) {
|
|
2188
|
+
signal?.throwIfAborted();
|
|
2189
|
+
return environmentFailure(error, context.apiUrl);
|
|
2190
|
+
}
|
|
2191
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
2192
|
+
return failure(
|
|
2193
|
+
"repository_not_connected",
|
|
2194
|
+
`${repository} is not connected to Primitive`,
|
|
2195
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
2196
|
+
);
|
|
2197
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2198
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2199
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
2200
|
+
return failure(
|
|
2201
|
+
"challenge_open",
|
|
2202
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
2203
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
2204
|
+
);
|
|
2205
|
+
if (answer.status === 429)
|
|
2206
|
+
return failure(
|
|
2207
|
+
"too_many_challenges",
|
|
2208
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
2209
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
2210
|
+
);
|
|
2211
|
+
const challengeId = answer.value?.challengeId;
|
|
2212
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
2213
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
2214
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2215
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2216
|
+
context.apiUrl
|
|
2217
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2218
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
2219
|
+
attempt.challengeId = challengeId;
|
|
2220
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
2221
|
+
return pushSessionBranch(
|
|
2222
|
+
root,
|
|
2223
|
+
repository,
|
|
2224
|
+
branch,
|
|
2225
|
+
baseSha,
|
|
2226
|
+
{ challengeId, challengeExpiresAt },
|
|
2227
|
+
signal
|
|
2228
|
+
);
|
|
2229
|
+
}
|
|
2230
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
2231
|
+
const push = await git(
|
|
2232
|
+
root,
|
|
2233
|
+
[
|
|
2234
|
+
"-c",
|
|
2235
|
+
"core.hooksPath=/dev/null",
|
|
2236
|
+
"-c",
|
|
2237
|
+
"push.followTags=false",
|
|
2238
|
+
"-c",
|
|
2239
|
+
"push.recurseSubmodules=no",
|
|
2240
|
+
"-c",
|
|
2241
|
+
"push.gpgSign=false",
|
|
2242
|
+
"-c",
|
|
2243
|
+
"push.pushOption=",
|
|
2244
|
+
"push",
|
|
2245
|
+
"--no-verify",
|
|
2246
|
+
"--no-follow-tags",
|
|
2247
|
+
"--no-recurse-submodules",
|
|
2248
|
+
"--no-signed",
|
|
2249
|
+
"--quiet",
|
|
2250
|
+
"origin",
|
|
2251
|
+
`${baseSha}:refs/heads/${branch}`
|
|
2252
|
+
],
|
|
2253
|
+
signal
|
|
2254
|
+
);
|
|
2255
|
+
if (!push.ok)
|
|
2256
|
+
return push.timedOut ? failure(
|
|
2257
|
+
"push_timeout",
|
|
2258
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
|
|
2259
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
2260
|
+
) : failure(
|
|
2261
|
+
"push_refused",
|
|
2262
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
2263
|
+
`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}`
|
|
2264
|
+
);
|
|
2265
|
+
return { ...challenge, repository };
|
|
2266
|
+
}
|
|
2267
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
2268
|
+
let context;
|
|
2269
|
+
try {
|
|
2270
|
+
context = sessionContext(deps);
|
|
2271
|
+
} catch (error) {
|
|
2272
|
+
return failure(
|
|
2273
|
+
"environment_credential_invalid",
|
|
2274
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
2275
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
2276
|
+
);
|
|
2277
|
+
}
|
|
2278
|
+
if ("status" in context) return context;
|
|
2279
|
+
const ctx = context;
|
|
2280
|
+
const startedAt = Date.now();
|
|
2281
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
2282
|
+
return withFileLock(
|
|
2283
|
+
ctx.lockPath,
|
|
2284
|
+
async () => {
|
|
2285
|
+
const record = readToken(ctx);
|
|
2286
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
2287
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
2288
|
+
if (record) {
|
|
2289
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
2290
|
+
if (refreshed.status === "ok") {
|
|
2291
|
+
writeToken(ctx, refreshed.record);
|
|
2292
|
+
return identified(refreshed.record, true);
|
|
2293
|
+
}
|
|
2294
|
+
if (refreshed.status === "refused") {
|
|
2295
|
+
rmSync5(ctx.tokenPath, { force: true });
|
|
2296
|
+
writeState(ctx, {
|
|
2297
|
+
sessionId: ctx.sessionId,
|
|
2298
|
+
status: "failed",
|
|
2299
|
+
code: refreshed.failure.code,
|
|
2300
|
+
cause: refreshed.failure.cause,
|
|
2301
|
+
remedy: refreshed.failure.remedy,
|
|
2302
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
2303
|
+
at: Date.now()
|
|
2304
|
+
});
|
|
2305
|
+
return refreshed.failure;
|
|
2306
|
+
}
|
|
2307
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
2308
|
+
}
|
|
2309
|
+
const state = readState(ctx);
|
|
2310
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
2311
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
2312
|
+
if (!options.explicit) {
|
|
2313
|
+
if (!root || !(record || state))
|
|
2314
|
+
return failure(
|
|
2315
|
+
"not_identified",
|
|
2316
|
+
"this session has not identified who started it yet",
|
|
2317
|
+
RETRY_REMEDY
|
|
2318
|
+
);
|
|
2319
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
2320
|
+
} else if (state && state.at >= startedAt) {
|
|
2321
|
+
return outcomeFromState(state);
|
|
2322
|
+
}
|
|
2323
|
+
if (!root)
|
|
2324
|
+
return failure(
|
|
2325
|
+
"repository_missing",
|
|
2326
|
+
"this is not a git repository",
|
|
2327
|
+
"run it in the repository the session cloned"
|
|
2328
|
+
);
|
|
2329
|
+
const attempt = { root };
|
|
2330
|
+
const remember = (outcome) => {
|
|
2331
|
+
writeState(ctx, {
|
|
2332
|
+
sessionId: ctx.sessionId,
|
|
2333
|
+
status: outcome.status,
|
|
2334
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
2335
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
2336
|
+
githubLogin: outcome.githubLogin
|
|
2337
|
+
},
|
|
2338
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
2339
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
2340
|
+
repositoryRoot: root,
|
|
2341
|
+
branch: attempt.branch ?? state?.branch,
|
|
2342
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
2343
|
+
at: Date.now()
|
|
2344
|
+
});
|
|
2345
|
+
return outcome;
|
|
2346
|
+
};
|
|
2347
|
+
let challenge;
|
|
2348
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
2349
|
+
attempt.challengeId = state.challengeId;
|
|
2350
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2351
|
+
attempt.branch = state.branch;
|
|
2352
|
+
attempt.baseSha = state.baseSha;
|
|
2353
|
+
challenge = {
|
|
2354
|
+
challengeId: state.challengeId,
|
|
2355
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2356
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
2357
|
+
};
|
|
2358
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
2359
|
+
attempt.challengeId = state.challengeId;
|
|
2360
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2361
|
+
const exchanged2 = await exchangeChallenge(
|
|
2362
|
+
ctx,
|
|
2363
|
+
{
|
|
2364
|
+
challengeId: state.challengeId,
|
|
2365
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2366
|
+
githubLogin: state.githubLogin
|
|
2367
|
+
},
|
|
2368
|
+
root,
|
|
2369
|
+
deps,
|
|
2370
|
+
options.signal
|
|
2371
|
+
);
|
|
2372
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
2373
|
+
writeToken(ctx, exchanged2);
|
|
2374
|
+
return identified(exchanged2, false);
|
|
2375
|
+
} else if (!options.explicit) {
|
|
2376
|
+
return state ? outcomeFromState(state) : failure(
|
|
2377
|
+
"not_identified",
|
|
2378
|
+
"this session has not identified who started it yet",
|
|
2379
|
+
RETRY_REMEDY
|
|
2380
|
+
);
|
|
2381
|
+
} else {
|
|
2382
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
2383
|
+
if ("status" in pushed) return remember(pushed);
|
|
2384
|
+
challenge = pushed;
|
|
2385
|
+
}
|
|
2386
|
+
const verified = await pollChallenge(
|
|
2387
|
+
ctx.apiUrl,
|
|
2388
|
+
challenge.challengeId,
|
|
2389
|
+
challenge.repository,
|
|
2390
|
+
// A hook process waits only briefly for a late notice.
|
|
2391
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
2392
|
+
options.signal
|
|
2393
|
+
);
|
|
2394
|
+
if ("status" in verified) return remember(verified);
|
|
2395
|
+
const exchanged = await exchangeChallenge(
|
|
2396
|
+
ctx,
|
|
2397
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
2398
|
+
root,
|
|
2399
|
+
deps,
|
|
2400
|
+
options.signal
|
|
2401
|
+
);
|
|
2402
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
2403
|
+
writeToken(ctx, exchanged);
|
|
2404
|
+
return identified(exchanged, false);
|
|
2405
|
+
},
|
|
2406
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
2407
|
+
);
|
|
2408
|
+
}
|
|
2409
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
2410
|
+
const cached2 = cachedSessionCredential(deps);
|
|
2411
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
2412
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
2413
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2414
|
+
let outcome;
|
|
2415
|
+
try {
|
|
2416
|
+
outcome = await ensureSessionIdentity(
|
|
2417
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
2418
|
+
deps
|
|
2419
|
+
);
|
|
2420
|
+
} catch (error) {
|
|
2421
|
+
options.signal?.throwIfAborted();
|
|
2422
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2423
|
+
throw new MachineAuthError(
|
|
2424
|
+
"identity_unavailable",
|
|
2425
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
2426
|
+
);
|
|
2427
|
+
}
|
|
2428
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
2429
|
+
throw new MachineAuthError(
|
|
2430
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
2431
|
+
sessionIdentityMessage(outcome)
|
|
2432
|
+
);
|
|
2433
|
+
}
|
|
2434
|
+
|
|
987
2435
|
// src/lib/machine-credentials.ts
|
|
2436
|
+
function sessionScoped(deps) {
|
|
2437
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
2438
|
+
}
|
|
988
2439
|
var require2 = createRequire(import.meta.url);
|
|
989
2440
|
var SERVICE = "ai.primitive.prim.machine";
|
|
990
|
-
var
|
|
2441
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
991
2442
|
var PROFILE_FILE = "machine_profile.json";
|
|
992
|
-
var
|
|
2443
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
993
2444
|
var cached;
|
|
994
2445
|
function configurationDirectory(deps) {
|
|
995
2446
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
996
2447
|
}
|
|
997
2448
|
function apiUrlFor(deps) {
|
|
998
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
2449
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
999
2450
|
}
|
|
1000
|
-
function
|
|
1001
|
-
return
|
|
2451
|
+
function hash2(value) {
|
|
2452
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
1002
2453
|
}
|
|
1003
2454
|
function recordPath(directory, generation) {
|
|
1004
|
-
return
|
|
2455
|
+
return join8(directory, `machine_${generation}.json`);
|
|
1005
2456
|
}
|
|
1006
2457
|
function storageKey(directory, generation) {
|
|
1007
|
-
return `${
|
|
2458
|
+
return `${hash2(directory)}:${generation}`;
|
|
1008
2459
|
}
|
|
1009
2460
|
function environmentContextPath(deps, clientId) {
|
|
1010
|
-
return
|
|
2461
|
+
return join8(
|
|
1011
2462
|
configurationDirectory(deps),
|
|
1012
|
-
`machine_context_${
|
|
2463
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1013
2464
|
);
|
|
1014
2465
|
}
|
|
1015
2466
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -1068,14 +2519,14 @@ function readEnvironmentContext(environment, deps) {
|
|
|
1068
2519
|
}
|
|
1069
2520
|
}
|
|
1070
2521
|
function keyringEntry(key) {
|
|
1071
|
-
let directory =
|
|
2522
|
+
let directory = dirname5(fileURLToPath3(import.meta.url));
|
|
1072
2523
|
for (let depth = 0; depth < 5; depth++) {
|
|
1073
|
-
const loader =
|
|
2524
|
+
const loader = join8(directory, "native", "keyring.cjs");
|
|
1074
2525
|
if (existsSync3(loader)) {
|
|
1075
2526
|
const module2 = require2(loader);
|
|
1076
2527
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1077
2528
|
}
|
|
1078
|
-
directory =
|
|
2529
|
+
directory = dirname5(directory);
|
|
1079
2530
|
}
|
|
1080
2531
|
const module = require2("@napi-rs/keyring");
|
|
1081
2532
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
@@ -1087,7 +2538,7 @@ function protectPath(path, directory) {
|
|
|
1087
2538
|
}
|
|
1088
2539
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
1089
2540
|
const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
|
|
1090
|
-
|
|
2541
|
+
execFileSync2(
|
|
1091
2542
|
"powershell.exe",
|
|
1092
2543
|
[
|
|
1093
2544
|
"-NoProfile",
|
|
@@ -1100,7 +2551,7 @@ function protectPath(path, directory) {
|
|
|
1100
2551
|
}
|
|
1101
2552
|
function ensureDirectory(directory) {
|
|
1102
2553
|
mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
1103
|
-
if (
|
|
2554
|
+
if (lstatSync4(directory).isSymbolicLink())
|
|
1104
2555
|
throw new MachineAuthError(
|
|
1105
2556
|
"unsafe_storage",
|
|
1106
2557
|
"Credential directory must not be a symbolic link."
|
|
@@ -1112,17 +2563,20 @@ function writePrivate(path, value) {
|
|
|
1112
2563
|
`, { mode: 384 });
|
|
1113
2564
|
protectPath(path, false);
|
|
1114
2565
|
}
|
|
2566
|
+
function readMachineMetadata(path) {
|
|
2567
|
+
return readPrivate(path);
|
|
2568
|
+
}
|
|
1115
2569
|
function readPrivate(path) {
|
|
1116
2570
|
let raw;
|
|
1117
2571
|
try {
|
|
1118
|
-
const stat =
|
|
2572
|
+
const stat = lstatSync4(path);
|
|
1119
2573
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1120
2574
|
throw new MachineAuthError(
|
|
1121
2575
|
"unsafe_storage",
|
|
1122
2576
|
"Machine credential files must be owner-only regular files."
|
|
1123
2577
|
);
|
|
1124
2578
|
}
|
|
1125
|
-
raw =
|
|
2579
|
+
raw = readFileSync6(path, "utf8");
|
|
1126
2580
|
} catch (error) {
|
|
1127
2581
|
if (error.code === "ENOENT") return void 0;
|
|
1128
2582
|
throw error;
|
|
@@ -1167,13 +2621,101 @@ function parseProfile(value) {
|
|
|
1167
2621
|
};
|
|
1168
2622
|
}
|
|
1169
2623
|
function readMachineProfile(deps = {}) {
|
|
1170
|
-
const value = readPrivate(
|
|
2624
|
+
const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
|
|
1171
2625
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1172
2626
|
}
|
|
2627
|
+
var NETWORK_SECRET_AUTH = "network-secret";
|
|
2628
|
+
var NETWORK_TOKEN_AUTH = "network-token";
|
|
2629
|
+
var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
2630
|
+
var brokerKeys = /* @__PURE__ */ new Map();
|
|
2631
|
+
function networkSecretBrokerKey(deps, clientId) {
|
|
2632
|
+
const directory = configurationDirectory(deps);
|
|
2633
|
+
const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
2634
|
+
const known = brokerKeys.get(path);
|
|
2635
|
+
if (known) return known;
|
|
2636
|
+
ensureDirectory(directory);
|
|
2637
|
+
const read = () => {
|
|
2638
|
+
try {
|
|
2639
|
+
const stat = lstatSync4(path);
|
|
2640
|
+
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
2641
|
+
throw new MachineAuthError(
|
|
2642
|
+
"unsafe_storage",
|
|
2643
|
+
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
2644
|
+
true
|
|
2645
|
+
);
|
|
2646
|
+
const value = readFileSync6(path, "utf8").trim();
|
|
2647
|
+
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
2648
|
+
} catch (error) {
|
|
2649
|
+
if (error.code === "ENOENT") return void 0;
|
|
2650
|
+
throw error;
|
|
2651
|
+
}
|
|
2652
|
+
};
|
|
2653
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
2654
|
+
const existing = read();
|
|
2655
|
+
if (existing?.key) {
|
|
2656
|
+
brokerKeys.set(path, existing.key);
|
|
2657
|
+
return existing.key;
|
|
2658
|
+
}
|
|
2659
|
+
if (existing)
|
|
2660
|
+
throw new MachineAuthError(
|
|
2661
|
+
"unsafe_storage",
|
|
2662
|
+
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
2663
|
+
true
|
|
2664
|
+
);
|
|
2665
|
+
const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
|
|
2666
|
+
try {
|
|
2667
|
+
writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
|
|
2668
|
+
`, { mode: 384, flag: "wx" });
|
|
2669
|
+
protectPath(staged, false);
|
|
2670
|
+
linkSync(staged, path);
|
|
2671
|
+
} catch (error) {
|
|
2672
|
+
if (error.code !== "EEXIST") throw error;
|
|
2673
|
+
} finally {
|
|
2674
|
+
rmSync6(staged, { force: true });
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
const key = read()?.key;
|
|
2678
|
+
if (!key)
|
|
2679
|
+
throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
|
|
2680
|
+
brokerKeys.set(path, key);
|
|
2681
|
+
return key;
|
|
2682
|
+
}
|
|
1173
2683
|
function environmentCredentials(deps) {
|
|
1174
2684
|
const env = deps.env ?? process.env;
|
|
1175
|
-
const {
|
|
1176
|
-
|
|
2685
|
+
const {
|
|
2686
|
+
PRIM_M2M_CLIENT_ID: clientId,
|
|
2687
|
+
PRIM_M2M_CLIENT_SECRET: clientSecret,
|
|
2688
|
+
PRIM_M2M_CLIENT_AUTH: auth
|
|
2689
|
+
} = env;
|
|
2690
|
+
if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
|
|
2691
|
+
if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
|
|
2692
|
+
throw new MachineAuthError(
|
|
2693
|
+
"incomplete_machine_credentials",
|
|
2694
|
+
`PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
|
|
2695
|
+
);
|
|
2696
|
+
if (auth !== void 0) {
|
|
2697
|
+
if (!clientId || !/^client_[\w-]+$/u.test(clientId))
|
|
2698
|
+
throw new MachineAuthError(
|
|
2699
|
+
"incomplete_machine_credentials",
|
|
2700
|
+
`Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
|
|
2701
|
+
);
|
|
2702
|
+
if (clientSecret !== void 0)
|
|
2703
|
+
throw new MachineAuthError(
|
|
2704
|
+
"conflicting_credentials",
|
|
2705
|
+
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
2706
|
+
);
|
|
2707
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
2708
|
+
const credentials = {
|
|
2709
|
+
clientId,
|
|
2710
|
+
generation,
|
|
2711
|
+
...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
|
|
2712
|
+
};
|
|
2713
|
+
Object.defineProperty(credentials, "clientSecret", {
|
|
2714
|
+
enumerable: true,
|
|
2715
|
+
get: () => networkSecretBrokerKey(deps, clientId)
|
|
2716
|
+
});
|
|
2717
|
+
return credentials;
|
|
2718
|
+
}
|
|
1177
2719
|
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1178
2720
|
throw new MachineAuthError(
|
|
1179
2721
|
"incomplete_machine_credentials",
|
|
@@ -1183,12 +2725,12 @@ function environmentCredentials(deps) {
|
|
|
1183
2725
|
return {
|
|
1184
2726
|
clientId,
|
|
1185
2727
|
clientSecret,
|
|
1186
|
-
generation:
|
|
2728
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1187
2729
|
};
|
|
1188
2730
|
}
|
|
1189
2731
|
function hasMachineConfiguration(deps = {}) {
|
|
1190
2732
|
const env = deps.env ?? process.env;
|
|
1191
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(
|
|
2733
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join8(configurationDirectory(deps), PROFILE_FILE));
|
|
1192
2734
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1193
2735
|
throw new MachineAuthError(
|
|
1194
2736
|
"conflicting_credentials",
|
|
@@ -1200,6 +2742,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
1200
2742
|
}
|
|
1201
2743
|
function machineContext(deps = {}) {
|
|
1202
2744
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2745
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1203
2746
|
const environment = environmentCredentials(deps);
|
|
1204
2747
|
if (environment) {
|
|
1205
2748
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -1214,6 +2757,7 @@ function machineContext(deps = {}) {
|
|
|
1214
2757
|
return profile;
|
|
1215
2758
|
}
|
|
1216
2759
|
function cachedMachineCredential(deps = {}) {
|
|
2760
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1217
2761
|
const context = machineContext(deps);
|
|
1218
2762
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1219
2763
|
}
|
|
@@ -1222,9 +2766,11 @@ function machineSessionEnded(deps = {}) {
|
|
|
1222
2766
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1223
2767
|
if (!generation) return false;
|
|
1224
2768
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1225
|
-
return readPrivate(
|
|
2769
|
+
return readPrivate(join8(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1226
2770
|
}
|
|
1227
2771
|
var environmentTerminal;
|
|
2772
|
+
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
2773
|
+
var networkRejection;
|
|
1228
2774
|
async function loadRecord(profile, deps, signal) {
|
|
1229
2775
|
const directory = configurationDirectory(deps);
|
|
1230
2776
|
let value;
|
|
@@ -1284,10 +2830,12 @@ async function persistRecord(record, deps, signal) {
|
|
|
1284
2830
|
}
|
|
1285
2831
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1286
2832
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2833
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
1287
2834
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1288
2835
|
const apiUrl = apiUrlFor(deps);
|
|
1289
2836
|
const environment = environmentCredentials(deps);
|
|
1290
2837
|
if (environment) {
|
|
2838
|
+
const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
|
|
1291
2839
|
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
1292
2840
|
const directory2 = configurationDirectory(deps);
|
|
1293
2841
|
ensureDirectory(directory2);
|
|
@@ -1305,22 +2853,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1305
2853
|
writeEnvironmentContext(cached, deps);
|
|
1306
2854
|
return cached;
|
|
1307
2855
|
} catch (error) {
|
|
1308
|
-
if (error instanceof MachineAuthError && error.terminal)
|
|
2856
|
+
if (error instanceof MachineAuthError && error.terminal && !networkManaged)
|
|
1309
2857
|
environmentTerminal = environment.generation;
|
|
1310
2858
|
throw error;
|
|
1311
2859
|
}
|
|
1312
2860
|
}
|
|
1313
2861
|
return withFileLock(
|
|
1314
|
-
|
|
2862
|
+
join8(directory2, "credentials.lock"),
|
|
1315
2863
|
async () => {
|
|
1316
2864
|
if (machineSessionEnded(deps))
|
|
1317
2865
|
throw new MachineAuthError(
|
|
1318
2866
|
"machine_credentials_rejected",
|
|
1319
|
-
"Rotate the injected machine credentials.",
|
|
2867
|
+
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1320
2868
|
true
|
|
1321
2869
|
);
|
|
1322
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
2870
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
1323
2871
|
return cached;
|
|
2872
|
+
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
2873
|
+
throw networkRejection.error;
|
|
1324
2874
|
try {
|
|
1325
2875
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
1326
2876
|
directory2,
|
|
@@ -1329,13 +2879,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1329
2879
|
signal,
|
|
1330
2880
|
async () => {
|
|
1331
2881
|
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
2882
|
+
if (environment.tokenInjection) {
|
|
2883
|
+
const identity3 = await verifyInjectedMachineIdentity(
|
|
2884
|
+
apiUrl,
|
|
2885
|
+
environment.clientId,
|
|
2886
|
+
signal,
|
|
2887
|
+
deps.fetch
|
|
2888
|
+
);
|
|
2889
|
+
const tokens3 = {
|
|
2890
|
+
accessToken: "",
|
|
2891
|
+
expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
|
|
2892
|
+
};
|
|
2893
|
+
return { configuration: configuration2, tokens: tokens3, identity: identity3 };
|
|
2894
|
+
}
|
|
1332
2895
|
const tokens2 = await exchangeMachineCredentials(
|
|
1333
2896
|
configuration2,
|
|
1334
2897
|
environment.clientId,
|
|
1335
|
-
|
|
2898
|
+
// The broker key is not a client secret; the proxy supplies that.
|
|
2899
|
+
environment.secretInjection ? "" : environment.clientSecret,
|
|
1336
2900
|
signal,
|
|
1337
|
-
deps.fetch
|
|
1338
|
-
|
|
2901
|
+
deps.fetch,
|
|
2902
|
+
{ secretInjection: environment.secretInjection }
|
|
2903
|
+
).catch((error) => {
|
|
2904
|
+
if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
|
|
2905
|
+
throw new MachineAuthError(
|
|
2906
|
+
"network_secret_mismatch",
|
|
2907
|
+
`The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
|
|
2908
|
+
true
|
|
2909
|
+
);
|
|
2910
|
+
throw error;
|
|
2911
|
+
});
|
|
1339
2912
|
const identity2 = await verifyMachineIdentity(
|
|
1340
2913
|
apiUrl,
|
|
1341
2914
|
tokens2.accessToken,
|
|
@@ -1352,17 +2925,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1352
2925
|
...identity,
|
|
1353
2926
|
apiUrl,
|
|
1354
2927
|
generation: environment.generation,
|
|
1355
|
-
storage: "environment"
|
|
2928
|
+
storage: "environment",
|
|
2929
|
+
...environment.tokenInjection ? { tokenInjection: "network" } : {}
|
|
1356
2930
|
};
|
|
1357
2931
|
writeEnvironmentContext(cached, deps);
|
|
1358
2932
|
return cached;
|
|
1359
2933
|
} catch (error) {
|
|
2934
|
+
if (networkManaged && error instanceof MachineAuthError && error.terminal) {
|
|
2935
|
+
networkRejection = {
|
|
2936
|
+
generation: environment.generation,
|
|
2937
|
+
until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
|
|
2938
|
+
error
|
|
2939
|
+
};
|
|
2940
|
+
if (cached?.generation === environment.generation) cached = void 0;
|
|
2941
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2942
|
+
try {
|
|
2943
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2944
|
+
rmSync6(contextPath, { force: true });
|
|
2945
|
+
} catch {
|
|
2946
|
+
}
|
|
2947
|
+
throw error;
|
|
2948
|
+
}
|
|
1360
2949
|
if (error instanceof MachineAuthError && error.terminal) {
|
|
1361
2950
|
environmentTerminal = environment.generation;
|
|
1362
2951
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1363
2952
|
try {
|
|
1364
2953
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1365
|
-
|
|
2954
|
+
rmSync6(contextPath, { force: true });
|
|
1366
2955
|
} catch {
|
|
1367
2956
|
}
|
|
1368
2957
|
}
|
|
@@ -1376,7 +2965,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1376
2965
|
const expected = machineContext(deps);
|
|
1377
2966
|
const directory = configurationDirectory(deps);
|
|
1378
2967
|
return withFileLock(
|
|
1379
|
-
|
|
2968
|
+
join8(directory, "credentials.lock"),
|
|
1380
2969
|
async () => {
|
|
1381
2970
|
const profile = readMachineProfile(deps);
|
|
1382
2971
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -1391,7 +2980,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1391
2980
|
true
|
|
1392
2981
|
);
|
|
1393
2982
|
let record = await loadRecord(profile, deps, signal);
|
|
1394
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
2983
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
1395
2984
|
try {
|
|
1396
2985
|
const { tokens, identity } = await withMachineCooldown(
|
|
1397
2986
|
directory,
|
|
@@ -1426,7 +3015,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1426
3015
|
await persistRecord(record, deps, signal);
|
|
1427
3016
|
} catch (error) {
|
|
1428
3017
|
if (error instanceof MachineAuthError && error.terminal)
|
|
1429
|
-
writePrivate(
|
|
3018
|
+
writePrivate(join8(directory, "machine_terminal.json"), profile.generation);
|
|
1430
3019
|
throw error;
|
|
1431
3020
|
}
|
|
1432
3021
|
}
|
|
@@ -1437,6 +3026,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1437
3026
|
{ signal }
|
|
1438
3027
|
);
|
|
1439
3028
|
}
|
|
3029
|
+
async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
3030
|
+
const environment = environmentCredentials(deps);
|
|
3031
|
+
if (!environment?.tokenInjection)
|
|
3032
|
+
throw new MachineAuthError(
|
|
3033
|
+
"identity_changed",
|
|
3034
|
+
"Machine identity changed; restart the operation."
|
|
3035
|
+
);
|
|
3036
|
+
const directory = configurationDirectory(deps);
|
|
3037
|
+
ensureDirectory(directory);
|
|
3038
|
+
return forwardBrokerRequest({
|
|
3039
|
+
directory,
|
|
3040
|
+
apiUrl: apiUrlFor(deps),
|
|
3041
|
+
environment,
|
|
3042
|
+
env: deps.env ?? process.env,
|
|
3043
|
+
request: request3,
|
|
3044
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
3045
|
+
});
|
|
3046
|
+
}
|
|
1440
3047
|
function machineCaptureActor(deps = {}) {
|
|
1441
3048
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1442
3049
|
const context = machineContext(deps);
|
|
@@ -1454,25 +3061,37 @@ function machineCaptureActor(deps = {}) {
|
|
|
1454
3061
|
return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
|
|
1455
3062
|
}
|
|
1456
3063
|
function machineJournalBucket(identity) {
|
|
1457
|
-
return `_machine_${
|
|
3064
|
+
return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
|
|
3065
|
+
}
|
|
3066
|
+
function identityPending(actor) {
|
|
3067
|
+
return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
|
|
3068
|
+
}
|
|
3069
|
+
function machinePendingBucket(identity) {
|
|
3070
|
+
return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
3071
|
+
}
|
|
3072
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
3073
|
+
ensureDirectory(directory);
|
|
3074
|
+
}
|
|
3075
|
+
function writeMachineMetadata(path, value) {
|
|
3076
|
+
writePrivate(path, value);
|
|
1458
3077
|
}
|
|
1459
3078
|
|
|
1460
3079
|
// src/lib/credentials.ts
|
|
1461
3080
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
1462
|
-
var TOKEN_FILE_PATH =
|
|
1463
|
-
var REFRESH_TOKEN_PATH =
|
|
1464
|
-
var TOKEN_EXPIRES_PATH =
|
|
1465
|
-
var TERMINAL_REFRESH_PATH =
|
|
1466
|
-
var CREDENTIAL_METADATA_PATH =
|
|
1467
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
1468
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
1469
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3081
|
+
var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
|
|
3082
|
+
var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
|
|
3083
|
+
var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
|
|
3084
|
+
var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3085
|
+
var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3086
|
+
var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
|
|
3087
|
+
var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3088
|
+
var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
|
|
1470
3089
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
1471
3090
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
1472
3091
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
1473
3092
|
function readTrimmed(path) {
|
|
1474
3093
|
try {
|
|
1475
|
-
const value =
|
|
3094
|
+
const value = readFileSync7(path, "utf8").trim();
|
|
1476
3095
|
return value || void 0;
|
|
1477
3096
|
} catch {
|
|
1478
3097
|
return void 0;
|
|
@@ -1481,7 +3100,7 @@ function readTrimmed(path) {
|
|
|
1481
3100
|
function resolveAuthCredential(options = {}) {
|
|
1482
3101
|
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
1483
3102
|
const machine = cachedMachineCredential({ env: options.env });
|
|
1484
|
-
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
3103
|
+
return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1485
3104
|
}
|
|
1486
3105
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
1487
3106
|
if (envToken) return { token: envToken, source: "environment" };
|
|
@@ -1494,22 +3113,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
1494
3113
|
);
|
|
1495
3114
|
if (metadata.state === "legacy_broker") {
|
|
1496
3115
|
if (metadata.metadata) {
|
|
1497
|
-
const
|
|
1498
|
-
if (!
|
|
3116
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3117
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
1499
3118
|
return void 0;
|
|
1500
3119
|
}
|
|
1501
3120
|
}
|
|
1502
3121
|
return { token: stored, source: "token_file" };
|
|
1503
3122
|
}
|
|
1504
3123
|
if (metadata.state === "invalid") return void 0;
|
|
1505
|
-
const
|
|
1506
|
-
if (!
|
|
3124
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3125
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
1507
3126
|
return void 0;
|
|
1508
3127
|
}
|
|
1509
3128
|
return { token: stored, source: "token_file" };
|
|
1510
3129
|
}
|
|
1511
3130
|
function credentialFingerprint(value) {
|
|
1512
|
-
return
|
|
3131
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
1513
3132
|
}
|
|
1514
3133
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
1515
3134
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -1529,7 +3148,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
1529
3148
|
function readBoundedCredentialJson(path) {
|
|
1530
3149
|
let raw;
|
|
1531
3150
|
try {
|
|
1532
|
-
raw =
|
|
3151
|
+
raw = readFileSync7(path, "utf8");
|
|
1533
3152
|
} catch (error) {
|
|
1534
3153
|
return error.code === "ENOENT" ? void 0 : null;
|
|
1535
3154
|
}
|
|
@@ -1606,14 +3225,14 @@ function jwtOrganizationId(token) {
|
|
|
1606
3225
|
|
|
1607
3226
|
// src/binding.ts
|
|
1608
3227
|
var PRIM_CONFIG_DIR = primConfigDirectory();
|
|
1609
|
-
var SESSIONS_DIR =
|
|
3228
|
+
var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
|
|
1610
3229
|
var WORKSPACE_FILE = ".prim/workspace.json";
|
|
1611
3230
|
function readJsonSafe(path) {
|
|
1612
3231
|
if (!existsSync4(path)) {
|
|
1613
3232
|
return;
|
|
1614
3233
|
}
|
|
1615
3234
|
try {
|
|
1616
|
-
return JSON.parse(
|
|
3235
|
+
return JSON.parse(readFileSync8(path, "utf-8"));
|
|
1617
3236
|
} catch {
|
|
1618
3237
|
return;
|
|
1619
3238
|
}
|
|
@@ -1622,17 +3241,17 @@ function fromSessionMarker(sessionId) {
|
|
|
1622
3241
|
if (!sessionId) {
|
|
1623
3242
|
return;
|
|
1624
3243
|
}
|
|
1625
|
-
const marker = readJsonSafe(
|
|
3244
|
+
const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
|
|
1626
3245
|
return marker?.orgId;
|
|
1627
3246
|
}
|
|
1628
3247
|
function fromWorkspaceFile(startDir) {
|
|
1629
3248
|
let dir = startDir;
|
|
1630
3249
|
while (true) {
|
|
1631
|
-
const config = readJsonSafe(
|
|
3250
|
+
const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
|
|
1632
3251
|
if (config?.orgId) {
|
|
1633
3252
|
return config.orgId;
|
|
1634
3253
|
}
|
|
1635
|
-
const parent =
|
|
3254
|
+
const parent = dirname6(dir);
|
|
1636
3255
|
if (parent === dir) {
|
|
1637
3256
|
return;
|
|
1638
3257
|
}
|
|
@@ -1669,29 +3288,29 @@ import { existsSync as existsSync9 } from "fs";
|
|
|
1669
3288
|
|
|
1670
3289
|
// src/demo/diagnostics.ts
|
|
1671
3290
|
import { existsSync as existsSync8 } from "fs";
|
|
1672
|
-
import { join as
|
|
3291
|
+
import { join as join14 } from "path";
|
|
1673
3292
|
|
|
1674
3293
|
// src/lib/hook-runtime.ts
|
|
1675
|
-
import { createHash as
|
|
3294
|
+
import { createHash as createHash7, randomBytes as randomBytes4 } from "crypto";
|
|
1676
3295
|
import {
|
|
1677
3296
|
constants as constants2,
|
|
1678
3297
|
accessSync,
|
|
1679
3298
|
chmodSync as chmodSync2,
|
|
1680
3299
|
copyFileSync,
|
|
1681
3300
|
existsSync as existsSync6,
|
|
1682
|
-
lstatSync as
|
|
3301
|
+
lstatSync as lstatSync5,
|
|
1683
3302
|
mkdirSync as mkdirSync4,
|
|
1684
3303
|
mkdtempSync,
|
|
1685
|
-
readFileSync as
|
|
1686
|
-
readdirSync,
|
|
1687
|
-
realpathSync,
|
|
3304
|
+
readFileSync as readFileSync9,
|
|
3305
|
+
readdirSync as readdirSync2,
|
|
3306
|
+
realpathSync as realpathSync2,
|
|
1688
3307
|
renameSync as renameSync2,
|
|
1689
|
-
rmSync as
|
|
3308
|
+
rmSync as rmSync7,
|
|
1690
3309
|
statSync as statSync2,
|
|
1691
3310
|
utimesSync,
|
|
1692
|
-
writeFileSync as
|
|
3311
|
+
writeFileSync as writeFileSync4
|
|
1693
3312
|
} from "fs";
|
|
1694
|
-
import { delimiter, dirname as
|
|
3313
|
+
import { delimiter, dirname as dirname8, isAbsolute as isAbsolute4, join as join12, resolve as resolve2 } from "path";
|
|
1695
3314
|
|
|
1696
3315
|
// src/lib/git-hook-contract.ts
|
|
1697
3316
|
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
@@ -1741,7 +3360,7 @@ exit 0
|
|
|
1741
3360
|
// src/lib/native-keyring.ts
|
|
1742
3361
|
import { existsSync as existsSync5 } from "fs";
|
|
1743
3362
|
import { createRequire as createRequire2 } from "module";
|
|
1744
|
-
import { dirname as
|
|
3363
|
+
import { dirname as dirname7, join as join11 } from "path";
|
|
1745
3364
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
1746
3365
|
var require3 = createRequire2(import.meta.url);
|
|
1747
3366
|
|
|
@@ -1792,9 +3411,9 @@ exec "$prim_node" "$prim_entry" "$@"
|
|
|
1792
3411
|
`;
|
|
1793
3412
|
|
|
1794
3413
|
// src/demo/state.ts
|
|
1795
|
-
import { createHash as
|
|
1796
|
-
import { existsSync as existsSync7, lstatSync as
|
|
1797
|
-
import { join as
|
|
3414
|
+
import { createHash as createHash8, randomUUID as randomUUID3 } from "crypto";
|
|
3415
|
+
import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync10, readdirSync as readdirSync3 } from "fs";
|
|
3416
|
+
import { join as join13, resolve as resolve3 } from "path";
|
|
1798
3417
|
|
|
1799
3418
|
// src/generated/cli-http-v1.validators.js
|
|
1800
3419
|
var import_ucs2length = __toESM(require_ucs2length(), 1);
|
|
@@ -28482,15 +30101,15 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
|
|
|
28482
30101
|
|
|
28483
30102
|
// src/demo/state.ts
|
|
28484
30103
|
var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
28485
|
-
var demoDirectory = () =>
|
|
30104
|
+
var demoDirectory = () => join13(primConfigDirectory(), "demo");
|
|
28486
30105
|
var runPath = (id2) => {
|
|
28487
30106
|
if (!RUN_ID.test(id2)) throw new Error("invalid demo run ID");
|
|
28488
|
-
return
|
|
30107
|
+
return join13(demoDirectory(), "runs", `${id2}.json`);
|
|
28489
30108
|
};
|
|
28490
30109
|
function readDemoJson(path) {
|
|
28491
|
-
const stat =
|
|
30110
|
+
const stat = lstatSync6(path);
|
|
28492
30111
|
if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
|
|
28493
|
-
return JSON.parse(
|
|
30112
|
+
return JSON.parse(readFileSync10(path, "utf8"));
|
|
28494
30113
|
}
|
|
28495
30114
|
function saveDemoJson(path, value) {
|
|
28496
30115
|
atomicWriteFile(path, `${JSON.stringify(value)}
|
|
@@ -28527,11 +30146,11 @@ function demoCommand(run, action, choice, reason) {
|
|
|
28527
30146
|
].map(quote).join(" ");
|
|
28528
30147
|
}
|
|
28529
30148
|
function sessionKey(agent, session) {
|
|
28530
|
-
return
|
|
30149
|
+
return createHash8("sha256").update(`${agent}\0${session}`).digest("hex");
|
|
28531
30150
|
}
|
|
28532
30151
|
function exclusionPath(key) {
|
|
28533
30152
|
if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
|
|
28534
|
-
return
|
|
30153
|
+
return join13(demoDirectory(), "excluded-sessions", `${key}.json`);
|
|
28535
30154
|
}
|
|
28536
30155
|
function sessionExcluded(agent, session) {
|
|
28537
30156
|
if (typeof session !== "string" || !session) return false;
|
|
@@ -28570,7 +30189,7 @@ function demoArgv(command) {
|
|
|
28570
30189
|
}
|
|
28571
30190
|
|
|
28572
30191
|
// src/demo/diagnostics.ts
|
|
28573
|
-
var observationPath = (id2) =>
|
|
30192
|
+
var observationPath = (id2) => join14(demoDirectory(), "observations", `${id2}.json`);
|
|
28574
30193
|
function observeRun(id2, observation) {
|
|
28575
30194
|
try {
|
|
28576
30195
|
saveDemoJson(observationPath(id2), observation);
|
|
@@ -28657,22 +30276,38 @@ function observeDemoInvocation(envelope, agent, checkExclusion = true) {
|
|
|
28657
30276
|
|
|
28658
30277
|
// src/lib/activation.ts
|
|
28659
30278
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
28660
|
-
import { existsSync as
|
|
30279
|
+
import { existsSync as existsSync11, readFileSync as readFileSync12 } from "fs";
|
|
28661
30280
|
import { homedir as homedir2 } from "os";
|
|
28662
|
-
import { join as
|
|
30281
|
+
import { join as join16 } from "path";
|
|
30282
|
+
|
|
30283
|
+
// src/lib/cloud-prepared.ts
|
|
30284
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync11, rmSync as rmSync8, writeFileSync as writeFileSync5 } from "fs";
|
|
30285
|
+
import { join as join15 } from "path";
|
|
30286
|
+
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
30287
|
+
function cloudPreparedPath(env = process.env) {
|
|
30288
|
+
return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
30289
|
+
}
|
|
30290
|
+
function isPreparedCloudSession(env = process.env) {
|
|
30291
|
+
if (!isClaudeCloudSession(env)) return false;
|
|
30292
|
+
try {
|
|
30293
|
+
return existsSync10(cloudPreparedPath(env));
|
|
30294
|
+
} catch {
|
|
30295
|
+
return false;
|
|
30296
|
+
}
|
|
30297
|
+
}
|
|
28663
30298
|
|
|
28664
30299
|
// src/lib/demo-pause.ts
|
|
28665
|
-
import { execFileSync as
|
|
30300
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
28666
30301
|
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
28667
30302
|
var PAUSE_KEY = "prim.demoPause";
|
|
28668
|
-
var
|
|
28669
|
-
function
|
|
30303
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
30304
|
+
function git2(cwd, args) {
|
|
28670
30305
|
try {
|
|
28671
|
-
return
|
|
30306
|
+
return execFileSync3("git", args, {
|
|
28672
30307
|
cwd,
|
|
28673
30308
|
encoding: "utf-8",
|
|
28674
30309
|
stdio: ["ignore", "pipe", "ignore"],
|
|
28675
|
-
timeout:
|
|
30310
|
+
timeout: GIT_TIMEOUT_MS3
|
|
28676
30311
|
});
|
|
28677
30312
|
} catch {
|
|
28678
30313
|
return void 0;
|
|
@@ -28680,10 +30315,10 @@ function git(cwd, args) {
|
|
|
28680
30315
|
}
|
|
28681
30316
|
function setLocal(cwd, key, value) {
|
|
28682
30317
|
try {
|
|
28683
|
-
|
|
30318
|
+
execFileSync3(
|
|
28684
30319
|
"git",
|
|
28685
30320
|
value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
|
|
28686
|
-
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout:
|
|
30321
|
+
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
|
|
28687
30322
|
);
|
|
28688
30323
|
} catch (error) {
|
|
28689
30324
|
if (value !== null || error.status !== 5) throw error;
|
|
@@ -28697,7 +30332,7 @@ function parsePause(value) {
|
|
|
28697
30332
|
function readCaptureConfig(cwd) {
|
|
28698
30333
|
let active;
|
|
28699
30334
|
let pause;
|
|
28700
|
-
const out =
|
|
30335
|
+
const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
|
|
28701
30336
|
for (const line of out.split("\n")) {
|
|
28702
30337
|
const space3 = line.indexOf(" ");
|
|
28703
30338
|
const key = line.slice(0, space3).toLowerCase();
|
|
@@ -28722,225 +30357,13 @@ function healDemoPause(cwd, pause, options = {}) {
|
|
|
28722
30357
|
}
|
|
28723
30358
|
}
|
|
28724
30359
|
|
|
28725
|
-
// src/lib/git.ts
|
|
28726
|
-
import { execFileSync as execFileSync3 } from "child_process";
|
|
28727
|
-
import { createHash as createHash7 } from "crypto";
|
|
28728
|
-
import { lstatSync as lstatSync6, realpathSync as realpathSync2 } from "fs";
|
|
28729
|
-
import { basename as basename2, dirname as dirname8, isAbsolute as isAbsolute4, relative, resolve as resolve3, sep } from "path";
|
|
28730
|
-
var GIT_TIMEOUT_MS2 = 1e3;
|
|
28731
|
-
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
28732
|
-
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
28733
|
-
function gitToplevel(cwd) {
|
|
28734
|
-
try {
|
|
28735
|
-
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
28736
|
-
cwd,
|
|
28737
|
-
encoding: "utf-8",
|
|
28738
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
28739
|
-
timeout: GIT_TIMEOUT_MS2
|
|
28740
|
-
}).trim();
|
|
28741
|
-
} catch {
|
|
28742
|
-
return null;
|
|
28743
|
-
}
|
|
28744
|
-
}
|
|
28745
|
-
function gitValue(cwd, args) {
|
|
28746
|
-
try {
|
|
28747
|
-
const value = execFileSync3("git", args, {
|
|
28748
|
-
cwd,
|
|
28749
|
-
encoding: "utf-8",
|
|
28750
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
28751
|
-
timeout: GIT_TIMEOUT_MS2
|
|
28752
|
-
}).trim();
|
|
28753
|
-
return value || void 0;
|
|
28754
|
-
} catch {
|
|
28755
|
-
return void 0;
|
|
28756
|
-
}
|
|
28757
|
-
}
|
|
28758
|
-
function currentBranch(cwd) {
|
|
28759
|
-
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
28760
|
-
}
|
|
28761
|
-
function githubRepositoryFullName(cwd) {
|
|
28762
|
-
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
28763
|
-
if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
28764
|
-
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
28765
|
-
remote
|
|
28766
|
-
);
|
|
28767
|
-
const path = match?.[1] ?? match?.[2];
|
|
28768
|
-
if (!path) return null;
|
|
28769
|
-
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
28770
|
-
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
28771
|
-
return null;
|
|
28772
|
-
}
|
|
28773
|
-
return `${parts[0]}/${parts[1]}`;
|
|
28774
|
-
}
|
|
28775
|
-
function canonicalGitRoot(cwd) {
|
|
28776
|
-
try {
|
|
28777
|
-
const top = gitToplevel(cwd);
|
|
28778
|
-
return top ? realpathSync2.native(top) : null;
|
|
28779
|
-
} catch {
|
|
28780
|
-
return null;
|
|
28781
|
-
}
|
|
28782
|
-
}
|
|
28783
|
-
function relatedWorktreeTarget(path, cwd, origin) {
|
|
28784
|
-
let parent = dirname8(resolve3(cwd, path));
|
|
28785
|
-
while (true) {
|
|
28786
|
-
try {
|
|
28787
|
-
realpathSync2.native(parent);
|
|
28788
|
-
break;
|
|
28789
|
-
} catch {
|
|
28790
|
-
const next = dirname8(parent);
|
|
28791
|
-
if (next === parent) return null;
|
|
28792
|
-
parent = next;
|
|
28793
|
-
}
|
|
28794
|
-
}
|
|
28795
|
-
const target = resolveRepositoryContext(parent);
|
|
28796
|
-
if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
|
|
28797
|
-
const common = (root) => {
|
|
28798
|
-
const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
|
|
28799
|
-
try {
|
|
28800
|
-
return value ? realpathSync2.native(resolve3(root, value)) : void 0;
|
|
28801
|
-
} catch {
|
|
28802
|
-
return void 0;
|
|
28803
|
-
}
|
|
28804
|
-
};
|
|
28805
|
-
const originCommon = common(origin.repoRoot);
|
|
28806
|
-
return originCommon && originCommon === common(target.repoRoot) ? target : null;
|
|
28807
|
-
}
|
|
28808
|
-
function normalizeOriginRemote(remote) {
|
|
28809
|
-
const value = remote.trim();
|
|
28810
|
-
if (!value) return void 0;
|
|
28811
|
-
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
28812
|
-
if (scp?.host && scp.path) {
|
|
28813
|
-
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
28814
|
-
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
28815
|
-
}
|
|
28816
|
-
try {
|
|
28817
|
-
const url = new URL(value);
|
|
28818
|
-
url.username = "";
|
|
28819
|
-
url.password = "";
|
|
28820
|
-
url.search = "";
|
|
28821
|
-
url.hash = "";
|
|
28822
|
-
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
28823
|
-
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
28824
|
-
return void 0;
|
|
28825
|
-
} catch {
|
|
28826
|
-
return void 0;
|
|
28827
|
-
}
|
|
28828
|
-
}
|
|
28829
|
-
function opaqueRepoKey(source, value) {
|
|
28830
|
-
return `repo_v1_${createHash7("sha256").update(`${source}\0${value}`).digest("hex")}`;
|
|
28831
|
-
}
|
|
28832
|
-
function resolveRepositoryContext(cwd = process.cwd()) {
|
|
28833
|
-
const top = gitToplevel(cwd);
|
|
28834
|
-
if (!top) return null;
|
|
28835
|
-
let repoRoot;
|
|
28836
|
-
try {
|
|
28837
|
-
repoRoot = realpathSync2.native(top);
|
|
28838
|
-
} catch {
|
|
28839
|
-
repoRoot = resolve3(top);
|
|
28840
|
-
}
|
|
28841
|
-
const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
|
|
28842
|
-
const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
|
|
28843
|
-
const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
|
|
28844
|
-
if (normalizedOrigin) {
|
|
28845
|
-
return {
|
|
28846
|
-
repoRoot,
|
|
28847
|
-
repoKey: opaqueRepoKey("origin", normalizedOrigin),
|
|
28848
|
-
identitySource: "origin",
|
|
28849
|
-
repoFullName
|
|
28850
|
-
};
|
|
28851
|
-
}
|
|
28852
|
-
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
28853
|
-
if (roots && roots.length > 0) {
|
|
28854
|
-
return {
|
|
28855
|
-
repoRoot,
|
|
28856
|
-
repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
|
|
28857
|
-
identitySource: "root_commit",
|
|
28858
|
-
repoFullName
|
|
28859
|
-
};
|
|
28860
|
-
}
|
|
28861
|
-
return { repoRoot, repoFullName };
|
|
28862
|
-
}
|
|
28863
|
-
function nearestExistingAncestor(path) {
|
|
28864
|
-
const suffix = [];
|
|
28865
|
-
let cursor = path;
|
|
28866
|
-
while (true) {
|
|
28867
|
-
try {
|
|
28868
|
-
lstatSync6(cursor);
|
|
28869
|
-
break;
|
|
28870
|
-
} catch (error) {
|
|
28871
|
-
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
28872
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
28873
|
-
const parent = dirname8(cursor);
|
|
28874
|
-
if (parent === cursor) return null;
|
|
28875
|
-
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
28876
|
-
cursor = parent;
|
|
28877
|
-
}
|
|
28878
|
-
}
|
|
28879
|
-
try {
|
|
28880
|
-
return { real: realpathSync2.native(cursor), suffix };
|
|
28881
|
-
} catch {
|
|
28882
|
-
return null;
|
|
28883
|
-
}
|
|
28884
|
-
}
|
|
28885
|
-
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
28886
|
-
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
28887
|
-
return { ok: false, reason: "invalid_path" };
|
|
28888
|
-
}
|
|
28889
|
-
const absolute = resolve3(baseDir, filePath);
|
|
28890
|
-
const resolved = nearestExistingAncestor(absolute);
|
|
28891
|
-
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
28892
|
-
const target = resolve3(resolved.real, ...resolved.suffix);
|
|
28893
|
-
const rel = relative(context.repoRoot, target);
|
|
28894
|
-
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
28895
|
-
if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
28896
|
-
return { ok: false, reason: "outside_repository" };
|
|
28897
|
-
}
|
|
28898
|
-
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
28899
|
-
}
|
|
28900
|
-
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
28901
|
-
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
28902
|
-
return null;
|
|
28903
|
-
const absolute = resolve3(cwd, filePath);
|
|
28904
|
-
let target;
|
|
28905
|
-
try {
|
|
28906
|
-
const stat = lstatSync6(absolute);
|
|
28907
|
-
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
28908
|
-
target = realpathSync2.native(absolute);
|
|
28909
|
-
} catch (error) {
|
|
28910
|
-
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
28911
|
-
return null;
|
|
28912
|
-
}
|
|
28913
|
-
try {
|
|
28914
|
-
const parent = realpathSync2.native(dirname8(absolute));
|
|
28915
|
-
if (!lstatSync6(parent).isDirectory()) return null;
|
|
28916
|
-
target = resolve3(parent, basename2(absolute));
|
|
28917
|
-
} catch {
|
|
28918
|
-
return null;
|
|
28919
|
-
}
|
|
28920
|
-
}
|
|
28921
|
-
const rel = relative(repositoryRoot, target);
|
|
28922
|
-
if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
28923
|
-
return null;
|
|
28924
|
-
}
|
|
28925
|
-
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
28926
|
-
}
|
|
28927
|
-
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
28928
|
-
if (typeof contextOrCwd === "string") {
|
|
28929
|
-
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
28930
|
-
}
|
|
28931
|
-
return canonicalRepositoryPathScoped(
|
|
28932
|
-
filePath,
|
|
28933
|
-
contextOrCwd,
|
|
28934
|
-
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
28935
|
-
);
|
|
28936
|
-
}
|
|
28937
|
-
|
|
28938
30360
|
// src/lib/activation.ts
|
|
28939
30361
|
var PRIM_ACTIVE_KEY = "prim.active";
|
|
30362
|
+
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
28940
30363
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
28941
30364
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
28942
30365
|
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
28943
|
-
var
|
|
30366
|
+
var GIT_TIMEOUT_MS4 = 1e3;
|
|
28944
30367
|
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
28945
30368
|
var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
|
|
28946
30369
|
var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
|
|
@@ -28950,7 +30373,7 @@ function repoActiveFlag(cwd, strict = false) {
|
|
|
28950
30373
|
cwd,
|
|
28951
30374
|
encoding: "utf-8",
|
|
28952
30375
|
stdio: ["ignore", "pipe", "ignore"],
|
|
28953
|
-
timeout:
|
|
30376
|
+
timeout: GIT_TIMEOUT_MS4
|
|
28954
30377
|
}).trim();
|
|
28955
30378
|
if (value === "true") return "true";
|
|
28956
30379
|
if (value === "false") return "false";
|
|
@@ -28971,7 +30394,7 @@ function localGitConfigValue(cwd, key) {
|
|
|
28971
30394
|
cwd,
|
|
28972
30395
|
encoding: "utf-8",
|
|
28973
30396
|
stdio: ["ignore", "pipe", "ignore"],
|
|
28974
|
-
timeout:
|
|
30397
|
+
timeout: GIT_TIMEOUT_MS4
|
|
28975
30398
|
}).trim();
|
|
28976
30399
|
return value || void 0;
|
|
28977
30400
|
} catch {
|
|
@@ -28982,7 +30405,7 @@ function setLocalGitConfigValue(cwd, key, value) {
|
|
|
28982
30405
|
execFileSync4("git", ["config", "--local", key, value], {
|
|
28983
30406
|
cwd,
|
|
28984
30407
|
stdio: ["ignore", "ignore", "pipe"],
|
|
28985
|
-
timeout:
|
|
30408
|
+
timeout: GIT_TIMEOUT_MS4
|
|
28986
30409
|
});
|
|
28987
30410
|
}
|
|
28988
30411
|
function repoSyncId(cwd) {
|
|
@@ -29000,14 +30423,13 @@ function repositoryBindingState(cwd) {
|
|
|
29000
30423
|
if (marker !== void 0) return "invalid";
|
|
29001
30424
|
return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
|
|
29002
30425
|
}
|
|
29003
|
-
function
|
|
29004
|
-
const root = gitToplevel(cwd);
|
|
30426
|
+
function projectPrimInstallAt(root) {
|
|
29005
30427
|
if (root === null || root === homedir2()) return false;
|
|
29006
30428
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
29007
|
-
const path =
|
|
29008
|
-
if (
|
|
30429
|
+
const path = join16(root, rel);
|
|
30430
|
+
if (existsSync11(path)) {
|
|
29009
30431
|
try {
|
|
29010
|
-
const content2 =
|
|
30432
|
+
const content2 = readFileSync12(path, "utf-8");
|
|
29011
30433
|
if (PRIM_HOOK_BINS.some((bin) => content2.includes(bin))) return true;
|
|
29012
30434
|
} catch {
|
|
29013
30435
|
}
|
|
@@ -29015,12 +30437,27 @@ function hasProjectPrimInstall(cwd) {
|
|
|
29015
30437
|
}
|
|
29016
30438
|
return false;
|
|
29017
30439
|
}
|
|
30440
|
+
var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
|
|
30441
|
+
function declaresInactiveAt(root) {
|
|
30442
|
+
if (root === null || root === homedir2()) return false;
|
|
30443
|
+
if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
|
|
30444
|
+
const text = checkoutSettingsText(root);
|
|
30445
|
+
if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
|
|
30446
|
+
try {
|
|
30447
|
+
JSON.parse(text);
|
|
30448
|
+
return false;
|
|
30449
|
+
} catch {
|
|
30450
|
+
return true;
|
|
30451
|
+
}
|
|
30452
|
+
}
|
|
29018
30453
|
function isRepoActiveForCapture(cwd, options = {}) {
|
|
29019
30454
|
let { active: flag, pause } = readCaptureConfig(cwd);
|
|
29020
30455
|
if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
|
|
29021
30456
|
if (flag === "true") return true;
|
|
29022
30457
|
if (flag === "false") return false;
|
|
29023
|
-
|
|
30458
|
+
const root = gitToplevel(cwd);
|
|
30459
|
+
if (declaresInactiveAt(root)) return false;
|
|
30460
|
+
return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
|
|
29024
30461
|
}
|
|
29025
30462
|
function decisionIngestionStatus(cwd) {
|
|
29026
30463
|
return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
|
|
@@ -29104,14 +30541,14 @@ function publicDecisionResponse(value) {
|
|
|
29104
30541
|
}
|
|
29105
30542
|
|
|
29106
30543
|
// src/client.ts
|
|
29107
|
-
import { createHash as
|
|
29108
|
-
import { chmodSync as chmodSync4, existsSync as
|
|
30544
|
+
import { createHash as createHash9 } from "crypto";
|
|
30545
|
+
import { chmodSync as chmodSync4, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync9 } from "fs";
|
|
29109
30546
|
import { dirname as dirname9 } from "path";
|
|
29110
30547
|
|
|
29111
30548
|
// src/daemon/client-instance-id.ts
|
|
29112
|
-
import { randomBytes as
|
|
29113
|
-
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as
|
|
29114
|
-
import { join as
|
|
30549
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
30550
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
|
|
30551
|
+
import { join as join17 } from "path";
|
|
29115
30552
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
29116
30553
|
var INSTANCE_FILE_MODE = 384;
|
|
29117
30554
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -29148,7 +30585,7 @@ function readExisting(path) {
|
|
|
29148
30585
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
29149
30586
|
throw new Error("stored client instance identity is invalid");
|
|
29150
30587
|
}
|
|
29151
|
-
const raw =
|
|
30588
|
+
const raw = readFileSync13(path, "utf8");
|
|
29152
30589
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
29153
30590
|
if (raw !== value && raw !== `${value}
|
|
29154
30591
|
` || !isClientInstanceId(value)) {
|
|
@@ -29162,8 +30599,8 @@ function atomicWrite(path, value) {
|
|
|
29162
30599
|
}
|
|
29163
30600
|
async function getOrCreateClientInstanceId(options) {
|
|
29164
30601
|
const configDir = options.configDir;
|
|
29165
|
-
const path =
|
|
29166
|
-
const lockPath =
|
|
30602
|
+
const path = join17(configDir, "client_instance_id");
|
|
30603
|
+
const lockPath = join17(configDir, "client-instance.lock");
|
|
29167
30604
|
ensurePrivateConfigDirectory(configDir);
|
|
29168
30605
|
return withFileLock(
|
|
29169
30606
|
lockPath,
|
|
@@ -29172,7 +30609,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
29172
30609
|
if (existing !== void 0) {
|
|
29173
30610
|
return existing;
|
|
29174
30611
|
}
|
|
29175
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
30612
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
29176
30613
|
"base64url"
|
|
29177
30614
|
)}`;
|
|
29178
30615
|
if (!isClientInstanceId(generated)) {
|
|
@@ -29207,57 +30644,18 @@ async function ingestUploaderHeaders() {
|
|
|
29207
30644
|
return headers;
|
|
29208
30645
|
}
|
|
29209
30646
|
|
|
29210
|
-
// src/lib/terminal-safe.ts
|
|
29211
|
-
function replaceIsolatedSurrogates(value) {
|
|
29212
|
-
let out = "";
|
|
29213
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
29214
|
-
const unit = value.charCodeAt(index);
|
|
29215
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
29216
|
-
const next = value.charCodeAt(index + 1);
|
|
29217
|
-
if (next >= 56320 && next <= 57343) {
|
|
29218
|
-
out += value[index] + value[index + 1];
|
|
29219
|
-
index += 1;
|
|
29220
|
-
} else {
|
|
29221
|
-
out += "\uFFFD";
|
|
29222
|
-
}
|
|
29223
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
29224
|
-
out += "\uFFFD";
|
|
29225
|
-
} else {
|
|
29226
|
-
out += value[index];
|
|
29227
|
-
}
|
|
29228
|
-
}
|
|
29229
|
-
return out;
|
|
29230
|
-
}
|
|
29231
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
29232
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
29233
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
29234
|
-
point === 1564 || // Arabic letter mark
|
|
29235
|
-
point === 6158 || // Mongolian vowel separator
|
|
29236
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
29237
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
29238
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
29239
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
29240
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
29241
|
-
point >= 917504 && point <= 917631;
|
|
29242
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
29243
|
-
}
|
|
29244
|
-
function terminalSafeText(value) {
|
|
29245
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
29246
|
-
}
|
|
29247
|
-
function terminalSafeLine(value) {
|
|
29248
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
29249
|
-
}
|
|
29250
|
-
var stripControlChars = terminalSafeText;
|
|
29251
|
-
|
|
29252
30647
|
// src/client.ts
|
|
29253
30648
|
var CONFIG_DIR_MODE = 448;
|
|
29254
30649
|
var CREDENTIAL_FILE_MODE = 384;
|
|
29255
30650
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
29256
|
-
var
|
|
30651
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
29257
30652
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
30653
|
+
function authExpiredMessage() {
|
|
30654
|
+
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
30655
|
+
}
|
|
29258
30656
|
function readTrimmed2(path) {
|
|
29259
30657
|
try {
|
|
29260
|
-
const value =
|
|
30658
|
+
const value = readFileSync14(path, "utf8").trim();
|
|
29261
30659
|
return value || void 0;
|
|
29262
30660
|
} catch {
|
|
29263
30661
|
return void 0;
|
|
@@ -29267,14 +30665,14 @@ function getSiteUrl() {
|
|
|
29267
30665
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
29268
30666
|
}
|
|
29269
30667
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
29270
|
-
return primApiUrl?.trim() ||
|
|
30668
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
29271
30669
|
}
|
|
29272
30670
|
function expiresAtFor(token, expiresIn) {
|
|
29273
30671
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
29274
30672
|
}
|
|
29275
30673
|
function ensureConfigDirectory() {
|
|
29276
30674
|
const directory = dirname9(TOKEN_FILE_PATH);
|
|
29277
|
-
|
|
30675
|
+
mkdirSync6(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
29278
30676
|
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
29279
30677
|
}
|
|
29280
30678
|
function atomicWrite2(path, content2) {
|
|
@@ -29282,8 +30680,8 @@ function atomicWrite2(path, content2) {
|
|
|
29282
30680
|
atomicWriteFile(path, content2, { mode: CREDENTIAL_FILE_MODE });
|
|
29283
30681
|
}
|
|
29284
30682
|
function removeCredentialFile(path) {
|
|
29285
|
-
if (!
|
|
29286
|
-
|
|
30683
|
+
if (!existsSync12(path)) return false;
|
|
30684
|
+
rmSync9(path, { force: true });
|
|
29287
30685
|
return true;
|
|
29288
30686
|
}
|
|
29289
30687
|
function getTokenExpiresAt() {
|
|
@@ -29298,23 +30696,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
29298
30696
|
const expiresAt = getTokenExpiresAt();
|
|
29299
30697
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
29300
30698
|
}
|
|
29301
|
-
function refreshFingerprint(
|
|
29302
|
-
return
|
|
30699
|
+
function refreshFingerprint(refreshToken3) {
|
|
30700
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
29303
30701
|
}
|
|
29304
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
30702
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
29305
30703
|
return {
|
|
29306
30704
|
version: 1,
|
|
29307
30705
|
family: "legacy_broker",
|
|
29308
30706
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29309
|
-
refreshTokenHash: refreshFingerprint(
|
|
30707
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29310
30708
|
};
|
|
29311
30709
|
}
|
|
29312
|
-
function credentialFamilyMetadata(accessToken,
|
|
30710
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
29313
30711
|
const hashes = {
|
|
29314
30712
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29315
|
-
refreshTokenHash: refreshFingerprint(
|
|
30713
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29316
30714
|
};
|
|
29317
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
30715
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
29318
30716
|
}
|
|
29319
30717
|
function writeCredentialMigrationSentinel() {
|
|
29320
30718
|
atomicWrite2(
|
|
@@ -29326,11 +30724,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
29326
30724
|
`
|
|
29327
30725
|
);
|
|
29328
30726
|
}
|
|
29329
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
29330
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
30727
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
30728
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
29331
30729
|
return { state: "invalid" };
|
|
29332
30730
|
}
|
|
29333
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30731
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29334
30732
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
29335
30733
|
return { state: "invalid" };
|
|
29336
30734
|
}
|
|
@@ -29347,17 +30745,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
29347
30745
|
const metadata = readStoredCredentialMetadata();
|
|
29348
30746
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
29349
30747
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
29350
|
-
const
|
|
29351
|
-
if (!(accessToken &&
|
|
29352
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30748
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
30749
|
+
if (!(accessToken && refreshToken3)) return;
|
|
30750
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29353
30751
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29354
30752
|
`);
|
|
29355
30753
|
}
|
|
29356
30754
|
function terminalFingerprint() {
|
|
29357
30755
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
29358
30756
|
}
|
|
29359
|
-
function writeTerminalFingerprint(
|
|
29360
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
30757
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
30758
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
29361
30759
|
`);
|
|
29362
30760
|
}
|
|
29363
30761
|
function clearTerminalFingerprint() {
|
|
@@ -29366,20 +30764,20 @@ function clearTerminalFingerprint() {
|
|
|
29366
30764
|
function isSessionEnded() {
|
|
29367
30765
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
29368
30766
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
29369
|
-
const
|
|
30767
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
29370
30768
|
const ended = terminalFingerprint();
|
|
29371
|
-
return Boolean(
|
|
30769
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
29372
30770
|
}
|
|
29373
30771
|
function withCredentialLock(operation, options = {}) {
|
|
29374
30772
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
29375
30773
|
}
|
|
29376
30774
|
function commitCredentialsUnlocked(credentials) {
|
|
29377
30775
|
const accessToken = credentials.accessToken.trim();
|
|
29378
|
-
const
|
|
29379
|
-
if (!accessToken || !
|
|
30776
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
30777
|
+
if (!accessToken || !refreshToken3) {
|
|
29380
30778
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
29381
30779
|
}
|
|
29382
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
30780
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
29383
30781
|
if (credentials.metadata !== void 0) {
|
|
29384
30782
|
preserveMarkerlessLegacyGeneration();
|
|
29385
30783
|
writeCredentialMigrationSentinel();
|
|
@@ -29387,10 +30785,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
29387
30785
|
`);
|
|
29388
30786
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
29389
30787
|
`);
|
|
29390
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30788
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29391
30789
|
`);
|
|
29392
30790
|
} else {
|
|
29393
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
30791
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29394
30792
|
`);
|
|
29395
30793
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29396
30794
|
`);
|
|
@@ -29427,15 +30825,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
29427
30825
|
`
|
|
29428
30826
|
);
|
|
29429
30827
|
}
|
|
29430
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
30828
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
29431
30829
|
const current = readStoredCredentialMetadata();
|
|
29432
30830
|
if (expected.state === "legacy_broker") {
|
|
29433
30831
|
if (current.state !== "legacy_broker") return false;
|
|
29434
30832
|
if (!expected.metadata) return current.metadata === void 0;
|
|
29435
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
30833
|
+
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;
|
|
29436
30834
|
}
|
|
29437
30835
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
29438
|
-
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(
|
|
30836
|
+
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;
|
|
29439
30837
|
}
|
|
29440
30838
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
29441
30839
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -29604,7 +31002,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
29604
31002
|
);
|
|
29605
31003
|
}
|
|
29606
31004
|
var _refreshInFlight;
|
|
29607
|
-
function
|
|
31005
|
+
function refreshToken2(options = {}) {
|
|
29608
31006
|
if (hasMachineConfiguration())
|
|
29609
31007
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
29610
31008
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -29636,7 +31034,7 @@ var CliManagementResponseError = class extends Error {
|
|
|
29636
31034
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
29637
31035
|
async function managementResponseValue(response) {
|
|
29638
31036
|
if (response.status === 401) {
|
|
29639
|
-
throw new HttpError(401,
|
|
31037
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29640
31038
|
}
|
|
29641
31039
|
let value;
|
|
29642
31040
|
try {
|
|
@@ -29658,23 +31056,50 @@ function selectedCredential() {
|
|
|
29658
31056
|
}
|
|
29659
31057
|
return _cachedCredential;
|
|
29660
31058
|
}
|
|
31059
|
+
async function requestHeaders(method, path) {
|
|
31060
|
+
return {
|
|
31061
|
+
"Content-Type": "application/json",
|
|
31062
|
+
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
31063
|
+
};
|
|
31064
|
+
}
|
|
29661
31065
|
async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
29662
31066
|
return fetch(`${siteUrl}${path}`, {
|
|
29663
31067
|
method,
|
|
29664
|
-
headers: {
|
|
29665
|
-
Authorization: `Bearer ${token}`,
|
|
29666
|
-
"Content-Type": "application/json",
|
|
29667
|
-
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
29668
|
-
},
|
|
31068
|
+
headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
|
|
29669
31069
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
29670
31070
|
signal: options?.signal,
|
|
29671
31071
|
redirect: options?.redirect
|
|
29672
31072
|
});
|
|
29673
31073
|
}
|
|
31074
|
+
async function fetchAsMachine(credential, method, path, body, options) {
|
|
31075
|
+
if (!credential.tokenInjection)
|
|
31076
|
+
return fetchWithToken(
|
|
31077
|
+
method,
|
|
31078
|
+
path,
|
|
31079
|
+
body,
|
|
31080
|
+
{ ...options, redirect: "error" },
|
|
31081
|
+
credential.accessToken,
|
|
31082
|
+
credential.apiUrl
|
|
31083
|
+
);
|
|
31084
|
+
try {
|
|
31085
|
+
return await forwardMachineRequest(
|
|
31086
|
+
{
|
|
31087
|
+
method,
|
|
31088
|
+
path,
|
|
31089
|
+
headers: await requestHeaders(method, path),
|
|
31090
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
31091
|
+
},
|
|
31092
|
+
options.signal
|
|
31093
|
+
);
|
|
31094
|
+
} catch (error) {
|
|
31095
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
31096
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
31097
|
+
}
|
|
31098
|
+
}
|
|
29674
31099
|
async function responseValue(response) {
|
|
29675
31100
|
if (!response.ok) {
|
|
29676
31101
|
if (response.status === 401) {
|
|
29677
|
-
throw new HttpError(401,
|
|
31102
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29678
31103
|
}
|
|
29679
31104
|
const errorBody = await response.json().catch(() => null);
|
|
29680
31105
|
const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
|
|
@@ -29701,14 +31126,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29701
31126
|
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
29702
31127
|
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
29703
31128
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
29704
|
-
let response = await
|
|
29705
|
-
method,
|
|
29706
|
-
path,
|
|
29707
|
-
body,
|
|
29708
|
-
{ ...requestOptions, redirect: "error" },
|
|
29709
|
-
current.accessToken,
|
|
29710
|
-
selected.apiUrl
|
|
29711
|
-
);
|
|
31129
|
+
let response = await fetchAsMachine(current, method, path, body, requestOptions);
|
|
29712
31130
|
if (response.status === 401) {
|
|
29713
31131
|
const renewed = await acquireMachineCredential({
|
|
29714
31132
|
force: true,
|
|
@@ -29717,19 +31135,14 @@ async function machineClient(options = {}, management = false) {
|
|
|
29717
31135
|
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
29718
31136
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
29719
31137
|
}
|
|
29720
|
-
response = await
|
|
29721
|
-
method,
|
|
29722
|
-
path,
|
|
29723
|
-
body,
|
|
29724
|
-
{ ...requestOptions, redirect: "error" },
|
|
29725
|
-
renewed.accessToken,
|
|
29726
|
-
renewed.apiUrl
|
|
29727
|
-
);
|
|
31138
|
+
response = await fetchAsMachine(renewed, method, path, body, requestOptions);
|
|
29728
31139
|
}
|
|
29729
31140
|
if (response.status === 401)
|
|
29730
31141
|
throw new HttpError(
|
|
29731
31142
|
401,
|
|
29732
|
-
"Machine access was rejected.
|
|
31143
|
+
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(
|
|
31144
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
31145
|
+
)
|
|
29733
31146
|
);
|
|
29734
31147
|
return parse2(response);
|
|
29735
31148
|
};
|
|
@@ -29739,7 +31152,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29739
31152
|
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
29740
31153
|
};
|
|
29741
31154
|
}
|
|
29742
|
-
async function
|
|
31155
|
+
async function request2(method, path, body, options) {
|
|
29743
31156
|
const machine = await machineClient(options);
|
|
29744
31157
|
if (machine)
|
|
29745
31158
|
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
@@ -29748,17 +31161,17 @@ async function request(method, path, body, options) {
|
|
|
29748
31161
|
let refreshAttempted = false;
|
|
29749
31162
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
29750
31163
|
refreshAttempted = true;
|
|
29751
|
-
const token = await
|
|
31164
|
+
const token = await refreshToken2({
|
|
29752
31165
|
signal: options?.signal,
|
|
29753
31166
|
quiet: options?.quietRefresh
|
|
29754
31167
|
});
|
|
29755
31168
|
if (token) credential = { token, source: "token_file" };
|
|
29756
31169
|
}
|
|
29757
31170
|
if (!credential) {
|
|
29758
|
-
throw new HttpError(401,
|
|
31171
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29759
31172
|
}
|
|
29760
31173
|
if (isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
29761
|
-
throw new HttpError(401,
|
|
31174
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29762
31175
|
}
|
|
29763
31176
|
const tokenUsed = credential.token;
|
|
29764
31177
|
let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
|
|
@@ -29767,7 +31180,7 @@ async function request(method, path, body, options) {
|
|
|
29767
31180
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
29768
31181
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
29769
31182
|
refreshAttempted = true;
|
|
29770
|
-
retryToken = await
|
|
31183
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
29771
31184
|
}
|
|
29772
31185
|
if (retryToken) {
|
|
29773
31186
|
_cachedCredential = {
|
|
@@ -29781,8 +31194,8 @@ async function request(method, path, body, options) {
|
|
|
29781
31194
|
}
|
|
29782
31195
|
function getClient() {
|
|
29783
31196
|
return {
|
|
29784
|
-
get: (path, options) =>
|
|
29785
|
-
post: (path, body, options) =>
|
|
31197
|
+
get: (path, options) => request2("GET", path, void 0, options),
|
|
31198
|
+
post: (path, body, options) => request2("POST", path, body, options)
|
|
29786
31199
|
};
|
|
29787
31200
|
}
|
|
29788
31201
|
async function getPinnedClient(options = {}) {
|
|
@@ -29791,14 +31204,14 @@ async function getPinnedClient(options = {}) {
|
|
|
29791
31204
|
const siteUrl = getSiteUrl();
|
|
29792
31205
|
let credential = selectedCredential();
|
|
29793
31206
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
29794
|
-
const token2 = await
|
|
31207
|
+
const token2 = await refreshToken2({
|
|
29795
31208
|
signal: options.signal,
|
|
29796
31209
|
quiet: options.quietRefresh
|
|
29797
31210
|
});
|
|
29798
31211
|
if (token2) credential = { token: token2, source: "token_file" };
|
|
29799
31212
|
}
|
|
29800
31213
|
if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
29801
|
-
throw new HttpError(401,
|
|
31214
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29802
31215
|
}
|
|
29803
31216
|
const token = credential.token;
|
|
29804
31217
|
const pinnedRequest = async (method, path, body, requestOptions) => responseValue(await fetchWithToken(method, path, body, requestOptions, token, siteUrl));
|
|
@@ -30170,17 +31583,17 @@ import {
|
|
|
30170
31583
|
closeSync as closeSync2,
|
|
30171
31584
|
fchmodSync as fchmodSync2,
|
|
30172
31585
|
fsyncSync as fsyncSync2,
|
|
30173
|
-
linkSync,
|
|
31586
|
+
linkSync as linkSync2,
|
|
30174
31587
|
lstatSync as lstatSync8,
|
|
30175
|
-
mkdirSync as
|
|
31588
|
+
mkdirSync as mkdirSync7,
|
|
30176
31589
|
openSync as openSync2,
|
|
30177
|
-
readFileSync as
|
|
31590
|
+
readFileSync as readFileSync15,
|
|
30178
31591
|
statSync as statSync3,
|
|
30179
31592
|
unlinkSync,
|
|
30180
|
-
writeFileSync as
|
|
31593
|
+
writeFileSync as writeFileSync6
|
|
30181
31594
|
} from "fs";
|
|
30182
|
-
import { dirname as dirname10, isAbsolute as isAbsolute5, join as
|
|
30183
|
-
var WORKSPACE_ID_RELATIVE_PATH =
|
|
31595
|
+
import { dirname as dirname10, isAbsolute as isAbsolute5, join as join19, resolve as resolve5 } from "path";
|
|
31596
|
+
var WORKSPACE_ID_RELATIVE_PATH = join19("prim", "workspace-id");
|
|
30184
31597
|
var MAX_ANCESTORS = 64;
|
|
30185
31598
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
30186
31599
|
var MAX_ID_FILE_BYTES = 128;
|
|
@@ -30239,19 +31652,19 @@ function resolveWorkspaceIdPath(cwd) {
|
|
|
30239
31652
|
function resolveFromFilesystem(cwd) {
|
|
30240
31653
|
let current = resolve5(cwd);
|
|
30241
31654
|
for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
|
|
30242
|
-
const dotGit =
|
|
31655
|
+
const dotGit = join19(current, ".git");
|
|
30243
31656
|
try {
|
|
30244
31657
|
const stat = lstatSync8(dotGit);
|
|
30245
31658
|
if (stat.isDirectory() && isGitDirectory(dotGit)) {
|
|
30246
|
-
return
|
|
31659
|
+
return join19(dotGit, WORKSPACE_ID_RELATIVE_PATH);
|
|
30247
31660
|
}
|
|
30248
31661
|
if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
|
|
30249
|
-
const contents =
|
|
31662
|
+
const contents = readFileSync15(dotGit, "utf8");
|
|
30250
31663
|
const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
|
|
30251
31664
|
if (match?.[1]) {
|
|
30252
31665
|
const gitDirectory = isAbsolute5(match[1]) ? resolve5(match[1]) : resolve5(current, match[1]);
|
|
30253
31666
|
if (isGitDirectory(gitDirectory)) {
|
|
30254
|
-
return
|
|
31667
|
+
return join19(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
|
|
30255
31668
|
}
|
|
30256
31669
|
}
|
|
30257
31670
|
}
|
|
@@ -30270,7 +31683,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
30270
31683
|
}
|
|
30271
31684
|
function isGitDirectory(path) {
|
|
30272
31685
|
try {
|
|
30273
|
-
return statSync3(
|
|
31686
|
+
return statSync3(join19(path, "HEAD")).isFile();
|
|
30274
31687
|
} catch {
|
|
30275
31688
|
return false;
|
|
30276
31689
|
}
|
|
@@ -30289,7 +31702,7 @@ function inspectPath(path) {
|
|
|
30289
31702
|
return { status: "corrupt", path, reason: "invalid_content" };
|
|
30290
31703
|
}
|
|
30291
31704
|
try {
|
|
30292
|
-
const contents =
|
|
31705
|
+
const contents = readFileSync15(path, "utf8");
|
|
30293
31706
|
const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
|
|
30294
31707
|
if ((contents === workspaceId || contents === `${workspaceId}
|
|
30295
31708
|
`) && isCanonicalWorkspaceId(workspaceId)) {
|
|
@@ -30308,11 +31721,11 @@ function inspectPath(path) {
|
|
|
30308
31721
|
function createWorkspaceId(path) {
|
|
30309
31722
|
const parent = dirname10(path);
|
|
30310
31723
|
const workspaceId = randomUUID4();
|
|
30311
|
-
const temporaryPath =
|
|
31724
|
+
const temporaryPath = join19(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
|
|
30312
31725
|
let temporaryCreated = false;
|
|
30313
31726
|
let publishing = false;
|
|
30314
31727
|
try {
|
|
30315
|
-
|
|
31728
|
+
mkdirSync7(parent, { recursive: true, mode: 448 });
|
|
30316
31729
|
chmodSync5(parent, 448);
|
|
30317
31730
|
const fd = openSync2(
|
|
30318
31731
|
temporaryPath,
|
|
@@ -30321,7 +31734,7 @@ function createWorkspaceId(path) {
|
|
|
30321
31734
|
);
|
|
30322
31735
|
temporaryCreated = true;
|
|
30323
31736
|
try {
|
|
30324
|
-
|
|
31737
|
+
writeFileSync6(fd, `${workspaceId}
|
|
30325
31738
|
`, "utf8");
|
|
30326
31739
|
fchmodSync2(fd, 384);
|
|
30327
31740
|
fsyncSync2(fd);
|
|
@@ -30329,7 +31742,7 @@ function createWorkspaceId(path) {
|
|
|
30329
31742
|
closeSync2(fd);
|
|
30330
31743
|
}
|
|
30331
31744
|
publishing = true;
|
|
30332
|
-
|
|
31745
|
+
linkSync2(temporaryPath, path);
|
|
30333
31746
|
return { status: "ready", workspaceId, path, created: true };
|
|
30334
31747
|
} catch (error) {
|
|
30335
31748
|
if (publishing && errorCode(error) === "EEXIST") return inspectAfterRace(path);
|
|
@@ -30378,29 +31791,29 @@ function parseAgent(argv) {
|
|
|
30378
31791
|
}
|
|
30379
31792
|
|
|
30380
31793
|
// src/hooks/codex-context.ts
|
|
30381
|
-
import { createHash as
|
|
31794
|
+
import { createHash as createHash11, randomBytes as randomBytes7 } from "crypto";
|
|
30382
31795
|
import {
|
|
30383
31796
|
chmodSync as chmodSync6,
|
|
30384
|
-
existsSync as
|
|
30385
|
-
mkdirSync as
|
|
30386
|
-
readFileSync as
|
|
30387
|
-
readdirSync as
|
|
31797
|
+
existsSync as existsSync13,
|
|
31798
|
+
mkdirSync as mkdirSync8,
|
|
31799
|
+
readFileSync as readFileSync16,
|
|
31800
|
+
readdirSync as readdirSync4,
|
|
30388
31801
|
renameSync as renameSync3,
|
|
30389
|
-
rmSync as
|
|
31802
|
+
rmSync as rmSync10,
|
|
30390
31803
|
statSync as statSync4,
|
|
30391
31804
|
unlinkSync as unlinkSync2,
|
|
30392
|
-
writeFileSync as
|
|
31805
|
+
writeFileSync as writeFileSync7
|
|
30393
31806
|
} from "fs";
|
|
30394
|
-
import { join as
|
|
31807
|
+
import { join as join21 } from "path";
|
|
30395
31808
|
|
|
30396
31809
|
// src/daemon/principal.ts
|
|
30397
|
-
import { createHash as
|
|
31810
|
+
import { createHash as createHash10 } from "crypto";
|
|
30398
31811
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
30399
31812
|
function boundedClaim(value) {
|
|
30400
31813
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
30401
31814
|
}
|
|
30402
31815
|
function sha256(value) {
|
|
30403
|
-
return
|
|
31816
|
+
return createHash10("sha256").update(value).digest("hex");
|
|
30404
31817
|
}
|
|
30405
31818
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
30406
31819
|
if (hasMachineConfiguration()) {
|
|
@@ -30454,14 +31867,14 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
30454
31867
|
|
|
30455
31868
|
// src/daemon/client.ts
|
|
30456
31869
|
import { createConnection } from "net";
|
|
30457
|
-
import { join as
|
|
30458
|
-
var SOCK_PATH =
|
|
31870
|
+
import { join as join20 } from "path";
|
|
31871
|
+
var SOCK_PATH = join20(primConfigDirectory(), "sock");
|
|
30459
31872
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
30460
31873
|
var nextRequestId = 1;
|
|
30461
31874
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
30462
31875
|
const id2 = nextRequestId++;
|
|
30463
31876
|
const caller = resolveDaemonPrincipal();
|
|
30464
|
-
const
|
|
31877
|
+
const request3 = {
|
|
30465
31878
|
id: id2,
|
|
30466
31879
|
method,
|
|
30467
31880
|
params,
|
|
@@ -30500,7 +31913,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
30500
31913
|
});
|
|
30501
31914
|
socket.on("connect", () => {
|
|
30502
31915
|
try {
|
|
30503
|
-
socket?.write(`${JSON.stringify(
|
|
31916
|
+
socket?.write(`${JSON.stringify(request3)}
|
|
30504
31917
|
`);
|
|
30505
31918
|
} catch {
|
|
30506
31919
|
clearTimeout(timer);
|
|
@@ -30545,7 +31958,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
30545
31958
|
}
|
|
30546
31959
|
|
|
30547
31960
|
// src/daemon/decision-digest-cache.ts
|
|
30548
|
-
import { randomBytes as
|
|
31961
|
+
import { randomBytes as randomBytes6 } from "crypto";
|
|
30549
31962
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
30550
31963
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
30551
31964
|
var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
|
|
@@ -30758,10 +32171,10 @@ function appendCodexContext(output, context) {
|
|
|
30758
32171
|
return next;
|
|
30759
32172
|
}
|
|
30760
32173
|
function stateRoot(namespace) {
|
|
30761
|
-
return
|
|
32174
|
+
return join21(primConfigDirectory(), namespace, "decision-digests");
|
|
30762
32175
|
}
|
|
30763
32176
|
function draftStateRoot(namespace) {
|
|
30764
|
-
return
|
|
32177
|
+
return join21(primConfigDirectory(), namespace, "decision-draft-deliveries");
|
|
30765
32178
|
}
|
|
30766
32179
|
function workspaceFor(cwd) {
|
|
30767
32180
|
try {
|
|
@@ -30772,13 +32185,13 @@ function workspaceFor(cwd) {
|
|
|
30772
32185
|
}
|
|
30773
32186
|
function statePath(args) {
|
|
30774
32187
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
|
|
30775
|
-
const key =
|
|
30776
|
-
return
|
|
32188
|
+
const key = createHash11("sha256").update(identity).digest("hex");
|
|
32189
|
+
return join21(stateRoot(args.namespace), `${key}.json`);
|
|
30777
32190
|
}
|
|
30778
32191
|
function draftStatePath(args) {
|
|
30779
32192
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
|
|
30780
|
-
const key =
|
|
30781
|
-
return
|
|
32193
|
+
const key = createHash11("sha256").update(identity).digest("hex");
|
|
32194
|
+
return join21(draftStateRoot(args.namespace), `${key}.json`);
|
|
30782
32195
|
}
|
|
30783
32196
|
function parseState(value) {
|
|
30784
32197
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
@@ -30816,31 +32229,31 @@ function parseDraftState(value) {
|
|
|
30816
32229
|
updatedAt: record.updatedAt
|
|
30817
32230
|
};
|
|
30818
32231
|
}
|
|
30819
|
-
function
|
|
30820
|
-
if (!
|
|
32232
|
+
function readState2(path) {
|
|
32233
|
+
if (!existsSync13(path)) return void 0;
|
|
30821
32234
|
try {
|
|
30822
|
-
return parseState(JSON.parse(
|
|
32235
|
+
return parseState(JSON.parse(readFileSync16(path, "utf8")));
|
|
30823
32236
|
} catch {
|
|
30824
32237
|
return void 0;
|
|
30825
32238
|
}
|
|
30826
32239
|
}
|
|
30827
32240
|
function readDraftState(path) {
|
|
30828
|
-
if (!
|
|
32241
|
+
if (!existsSync13(path)) return void 0;
|
|
30829
32242
|
try {
|
|
30830
|
-
return parseDraftState(JSON.parse(
|
|
32243
|
+
return parseDraftState(JSON.parse(readFileSync16(path, "utf8")));
|
|
30831
32244
|
} catch {
|
|
30832
32245
|
return void 0;
|
|
30833
32246
|
}
|
|
30834
32247
|
}
|
|
30835
32248
|
function writeStateFile(path, directory, state) {
|
|
30836
|
-
|
|
32249
|
+
mkdirSync8(directory, { recursive: true, mode: 448 });
|
|
30837
32250
|
chmodSync6(directory, 448);
|
|
30838
|
-
const temporary =
|
|
32251
|
+
const temporary = join21(
|
|
30839
32252
|
directory,
|
|
30840
|
-
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${
|
|
32253
|
+
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
|
|
30841
32254
|
);
|
|
30842
32255
|
try {
|
|
30843
|
-
|
|
32256
|
+
writeFileSync7(temporary, `${JSON.stringify(state)}
|
|
30844
32257
|
`, {
|
|
30845
32258
|
encoding: "utf8",
|
|
30846
32259
|
mode: 384,
|
|
@@ -30856,17 +32269,17 @@ function writeStateFile(path, directory, state) {
|
|
|
30856
32269
|
}
|
|
30857
32270
|
}
|
|
30858
32271
|
function cleanupStateFiles(directory, now) {
|
|
30859
|
-
if (!
|
|
32272
|
+
if (!existsSync13(directory)) return;
|
|
30860
32273
|
let names;
|
|
30861
32274
|
try {
|
|
30862
|
-
names =
|
|
32275
|
+
names = readdirSync4(directory);
|
|
30863
32276
|
} catch {
|
|
30864
32277
|
return;
|
|
30865
32278
|
}
|
|
30866
32279
|
const files = [];
|
|
30867
32280
|
const residue = [];
|
|
30868
32281
|
for (const name2 of names) {
|
|
30869
|
-
const path =
|
|
32282
|
+
const path = join21(directory, name2);
|
|
30870
32283
|
try {
|
|
30871
32284
|
const mtimeMs = statSync4(path).mtimeMs;
|
|
30872
32285
|
if (name2.endsWith(".json")) {
|
|
@@ -30888,7 +32301,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
30888
32301
|
for (const path of residue) {
|
|
30889
32302
|
try {
|
|
30890
32303
|
if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
|
|
30891
|
-
|
|
32304
|
+
rmSync10(path, { recursive: true, force: true });
|
|
30892
32305
|
}
|
|
30893
32306
|
} catch {
|
|
30894
32307
|
}
|
|
@@ -30974,7 +32387,7 @@ async function commitState(path, args, namespace) {
|
|
|
30974
32387
|
await withFileLock(
|
|
30975
32388
|
`${path}.lock`,
|
|
30976
32389
|
() => {
|
|
30977
|
-
const latest =
|
|
32390
|
+
const latest = readState2(path);
|
|
30978
32391
|
writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
|
|
30979
32392
|
cleanupStateFiles(stateRoot(namespace), args.now);
|
|
30980
32393
|
},
|
|
@@ -31021,7 +32434,7 @@ async function prepareCodexContext(options) {
|
|
|
31021
32434
|
const siteUrl = getSiteUrl();
|
|
31022
32435
|
const workspace = workspaceFor(options.cwd);
|
|
31023
32436
|
const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
|
|
31024
|
-
const previous =
|
|
32437
|
+
const previous = readState2(path);
|
|
31025
32438
|
const principal = resolveDaemonPrincipal();
|
|
31026
32439
|
const privatePath = principal ? draftStatePath({
|
|
31027
32440
|
cwd: options.cwd,
|
|
@@ -31171,17 +32584,17 @@ async function prepareCodexContext(options) {
|
|
|
31171
32584
|
}
|
|
31172
32585
|
|
|
31173
32586
|
// src/commands/cursor-install.ts
|
|
31174
|
-
import { existsSync as
|
|
32587
|
+
import { existsSync as existsSync15, readFileSync as readFileSync18 } from "fs";
|
|
31175
32588
|
import { homedir as homedir4 } from "os";
|
|
31176
|
-
import { isAbsolute as isAbsolute6, join as
|
|
32589
|
+
import { isAbsolute as isAbsolute6, join as join23 } from "path";
|
|
31177
32590
|
|
|
31178
32591
|
// src/lib/preflight-host.ts
|
|
31179
32592
|
import { execFileSync as execFileSync6 } from "child_process";
|
|
31180
32593
|
|
|
31181
32594
|
// src/commands/claude-install.ts
|
|
31182
|
-
import { existsSync as
|
|
32595
|
+
import { existsSync as existsSync14, lstatSync as lstatSync9, readFileSync as readFileSync17 } from "fs";
|
|
31183
32596
|
import { homedir as homedir3 } from "os";
|
|
31184
|
-
import { join as
|
|
32597
|
+
import { join as join22 } from "path";
|
|
31185
32598
|
var CAPTURE_BIN = "prim-hook";
|
|
31186
32599
|
var GATE_BIN = "prim-pre-tool-use";
|
|
31187
32600
|
var POST_TOOL_USE_BIN = "prim-post-tool-use";
|
|
@@ -31190,7 +32603,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
31190
32603
|
var STATUSLINE_BIN = "prim-statusline";
|
|
31191
32604
|
var STATUSLINE_ARGS = "";
|
|
31192
32605
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
31193
|
-
var USER_SCOPE_PATH =
|
|
32606
|
+
var USER_SCOPE_PATH = join22(homedir3(), ".claude", "settings.json");
|
|
31194
32607
|
function projectRoot() {
|
|
31195
32608
|
return gitToplevel() ?? process.cwd();
|
|
31196
32609
|
}
|
|
@@ -31270,20 +32683,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
|
|
|
31270
32683
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
31271
32684
|
if (explicit && isAbsolute6(explicit)) return explicit;
|
|
31272
32685
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
31273
|
-
if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return
|
|
31274
|
-
return
|
|
32686
|
+
if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join23(xdg, "cursor");
|
|
32687
|
+
return join23(home, ".cursor");
|
|
31275
32688
|
}
|
|
31276
32689
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
31277
|
-
return scope === "user" ?
|
|
32690
|
+
return scope === "user" ? join23(cursorConfigDirectory(), "hooks.json") : join23(root, ".cursor", "hooks.json");
|
|
31278
32691
|
}
|
|
31279
32692
|
function plainObject(value) {
|
|
31280
32693
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
31281
32694
|
}
|
|
31282
32695
|
function readCursorHooks(path) {
|
|
31283
|
-
if (!
|
|
32696
|
+
if (!existsSync15(path)) return {};
|
|
31284
32697
|
let parsed;
|
|
31285
32698
|
try {
|
|
31286
|
-
parsed = JSON.parse(
|
|
32699
|
+
parsed = JSON.parse(readFileSync18(path, "utf8"));
|
|
31287
32700
|
} catch {
|
|
31288
32701
|
throw new Error(`invalid Cursor hooks JSON at ${path}`);
|
|
31289
32702
|
}
|
|
@@ -31504,8 +32917,8 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
|
|
|
31504
32917
|
}
|
|
31505
32918
|
|
|
31506
32919
|
// src/hooks/redact.ts
|
|
31507
|
-
import { existsSync as
|
|
31508
|
-
import { join as
|
|
32920
|
+
import { existsSync as existsSync16, readFileSync as readFileSync19, statSync as statSync5 } from "fs";
|
|
32921
|
+
import { join as join24 } from "path";
|
|
31509
32922
|
import { Worker } from "worker_threads";
|
|
31510
32923
|
var USER_HOME_RULES = [
|
|
31511
32924
|
{
|
|
@@ -31549,6 +32962,11 @@ var DEFAULT_RULES = [
|
|
|
31549
32962
|
pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
|
|
31550
32963
|
reason: "aws-secret"
|
|
31551
32964
|
},
|
|
32965
|
+
{
|
|
32966
|
+
// `prim auth enroll --print-env` output an agent may write into a file.
|
|
32967
|
+
pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
|
|
32968
|
+
reason: "prim-m2m-secret"
|
|
32969
|
+
},
|
|
31552
32970
|
{ pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
|
|
31553
32971
|
{
|
|
31554
32972
|
pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
|
|
@@ -31581,15 +32999,15 @@ function normalizedWorkspaceFlags(value) {
|
|
|
31581
32999
|
return [...new Set(`g${requested}`)].sort().join("");
|
|
31582
33000
|
}
|
|
31583
33001
|
function loadWorkspaceRules(cwd) {
|
|
31584
|
-
const path =
|
|
31585
|
-
if (!
|
|
33002
|
+
const path = join24(cwd, WORKSPACE_FILE2);
|
|
33003
|
+
if (!existsSync16(path)) return [];
|
|
31586
33004
|
let cfg;
|
|
31587
33005
|
try {
|
|
31588
33006
|
if (statSync5(path).size > MAX_WORKSPACE_CONFIG_BYTES) {
|
|
31589
33007
|
debugRedaction(`ignoring oversized ${WORKSPACE_FILE2}`);
|
|
31590
33008
|
return [];
|
|
31591
33009
|
}
|
|
31592
|
-
cfg = JSON.parse(
|
|
33010
|
+
cfg = JSON.parse(readFileSync19(path, "utf-8"));
|
|
31593
33011
|
} catch {
|
|
31594
33012
|
debugRedaction(`ignoring unparseable ${WORKSPACE_FILE2}`);
|
|
31595
33013
|
return [];
|
|
@@ -37945,7 +39363,7 @@ var TokenGroup = class {
|
|
|
37945
39363
|
}
|
|
37946
39364
|
token(input, stack) {
|
|
37947
39365
|
let { parser: parser3 } = stack.p;
|
|
37948
|
-
|
|
39366
|
+
readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
|
|
37949
39367
|
}
|
|
37950
39368
|
};
|
|
37951
39369
|
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
|
|
@@ -37959,7 +39377,7 @@ var LocalTokenGroup = class {
|
|
|
37959
39377
|
let start = input.pos, skipped = 0;
|
|
37960
39378
|
for (; ; ) {
|
|
37961
39379
|
let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
|
|
37962
|
-
|
|
39380
|
+
readToken2(this.data, input, stack, 0, this.data, this.precTable);
|
|
37963
39381
|
if (input.token.value > -1)
|
|
37964
39382
|
break;
|
|
37965
39383
|
if (this.elseToken == null)
|
|
@@ -37992,7 +39410,7 @@ var ExternalTokenizer = class {
|
|
|
37992
39410
|
this.extend = !!options.extend;
|
|
37993
39411
|
}
|
|
37994
39412
|
};
|
|
37995
|
-
function
|
|
39413
|
+
function readToken2(data, input, stack, group, precTable, precOffset) {
|
|
37996
39414
|
let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
|
|
37997
39415
|
scan: for (; ; ) {
|
|
37998
39416
|
if ((groupMask & data[state]) == 0)
|
|
@@ -39805,7 +41223,7 @@ var newline2 = 10;
|
|
|
39805
41223
|
var carriageReturn = 13;
|
|
39806
41224
|
var space2 = 32;
|
|
39807
41225
|
var tab = 9;
|
|
39808
|
-
var
|
|
41226
|
+
var hash3 = 35;
|
|
39809
41227
|
var parenOpen = 40;
|
|
39810
41228
|
var dot2 = 46;
|
|
39811
41229
|
var braceOpen = 123;
|
|
@@ -39858,7 +41276,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
|
|
|
39858
41276
|
input.advance();
|
|
39859
41277
|
spaces2++;
|
|
39860
41278
|
}
|
|
39861
|
-
if (input.next == newline2 || input.next == carriageReturn || input.next ==
|
|
41279
|
+
if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
|
|
39862
41280
|
input.acceptToken(blankLineStart, -spaces2);
|
|
39863
41281
|
} else if (isLineBreak(input.next)) {
|
|
39864
41282
|
input.acceptToken(newline$1, 1);
|
|
@@ -39877,7 +41295,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
|
|
|
39877
41295
|
input.advance();
|
|
39878
41296
|
chars++;
|
|
39879
41297
|
}
|
|
39880
|
-
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next !=
|
|
41298
|
+
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
|
|
39881
41299
|
if (depth < context.indent) input.acceptToken(dedent, -chars);
|
|
39882
41300
|
else input.acceptToken(indent);
|
|
39883
41301
|
}
|
|
@@ -39951,7 +41369,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
|
|
|
39951
41369
|
for (let off = 0; ; off++) {
|
|
39952
41370
|
let next = input.peek(off);
|
|
39953
41371
|
if (next == space2 || next == tab) continue;
|
|
39954
|
-
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next !=
|
|
41372
|
+
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
|
|
39955
41373
|
input.acceptToken(printKeyword);
|
|
39956
41374
|
return;
|
|
39957
41375
|
}
|
|
@@ -41162,7 +42580,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
|
|
|
41162
42580
|
}
|
|
41163
42581
|
|
|
41164
42582
|
// src/hooks/normalize.ts
|
|
41165
|
-
import { createHash as
|
|
42583
|
+
import { createHash as createHash12 } from "crypto";
|
|
41166
42584
|
import { realpathSync as realpathSync4 } from "fs";
|
|
41167
42585
|
import { isAbsolute as isAbsolute8, resolve as resolve7 } from "path";
|
|
41168
42586
|
var HERMES_EVENT_MAP = {
|
|
@@ -41207,7 +42625,7 @@ function requiredId(value, field) {
|
|
|
41207
42625
|
}
|
|
41208
42626
|
function cursorToolUseId(value) {
|
|
41209
42627
|
if (SAFE_CORRELATION_ID_RE.test(value)) return value;
|
|
41210
|
-
return `cursor:tool:v1:${
|
|
42628
|
+
return `cursor:tool:v1:${createHash12("sha256").update(value).digest("hex")}`;
|
|
41211
42629
|
}
|
|
41212
42630
|
function workspaceCandidates(value) {
|
|
41213
42631
|
if (!Array.isArray(value)) return [];
|
|
@@ -41304,7 +42722,7 @@ function normalizeEnvelope(parsed, agent) {
|
|
|
41304
42722
|
]);
|
|
41305
42723
|
return {
|
|
41306
42724
|
...parsed,
|
|
41307
|
-
tool_use_id: `codex:fallback:v1:${
|
|
42725
|
+
tool_use_id: `codex:fallback:v1:${createHash12("sha256").update(stableToolIdentity).digest("hex")}`
|
|
41308
42726
|
};
|
|
41309
42727
|
}
|
|
41310
42728
|
return parsed;
|
|
@@ -41403,14 +42821,17 @@ function parseOrganizationBinding(value) {
|
|
|
41403
42821
|
}
|
|
41404
42822
|
function buildOrganizationBoundMoveRequest(batch, binding) {
|
|
41405
42823
|
const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
|
|
41406
|
-
const
|
|
42824
|
+
const request3 = {
|
|
41407
42825
|
batch: batch.map((move) => {
|
|
41408
42826
|
if (typeof move !== "object" || move === null || Array.isArray(move)) {
|
|
41409
42827
|
return move;
|
|
41410
42828
|
}
|
|
41411
42829
|
const { captureActor, ...wireMove } = move;
|
|
41412
42830
|
if (binding.captureAuthorityKind === "workos_m2m") {
|
|
41413
|
-
if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.
|
|
42831
|
+
if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || // An identity-pending actor names only its client and is bound to
|
|
42832
|
+
// the identity verified for it. Any other actor is a claim about a
|
|
42833
|
+
// verified identity and must match this one exactly.
|
|
42834
|
+
!identityPending(captureActor) && (captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId))
|
|
41414
42835
|
throw new InvalidJournalEnvelopeError();
|
|
41415
42836
|
} else if (captureActor) throw new InvalidJournalEnvelopeError();
|
|
41416
42837
|
return {
|
|
@@ -41426,40 +42847,40 @@ function buildOrganizationBoundMoveRequest(batch, binding) {
|
|
|
41426
42847
|
};
|
|
41427
42848
|
})
|
|
41428
42849
|
};
|
|
41429
|
-
if (!isMoveIngestRequest(
|
|
42850
|
+
if (!isMoveIngestRequest(request3)) {
|
|
41430
42851
|
throw new InvalidJournalEnvelopeError();
|
|
41431
42852
|
}
|
|
41432
|
-
return
|
|
42853
|
+
return request3;
|
|
41433
42854
|
}
|
|
41434
42855
|
|
|
41435
42856
|
// src/journal.ts
|
|
41436
42857
|
import {
|
|
41437
42858
|
appendFileSync,
|
|
41438
42859
|
closeSync as closeSync3,
|
|
41439
|
-
existsSync as
|
|
42860
|
+
existsSync as existsSync18,
|
|
41440
42861
|
fstatSync,
|
|
41441
|
-
mkdirSync as
|
|
42862
|
+
mkdirSync as mkdirSync9,
|
|
41442
42863
|
openSync as openSync3,
|
|
41443
42864
|
opendirSync,
|
|
41444
|
-
readFileSync as
|
|
42865
|
+
readFileSync as readFileSync21,
|
|
41445
42866
|
readSync,
|
|
41446
|
-
readdirSync as
|
|
42867
|
+
readdirSync as readdirSync6
|
|
41447
42868
|
} from "fs";
|
|
41448
|
-
import { dirname as dirname13, join as
|
|
42869
|
+
import { dirname as dirname13, join as join26 } from "path";
|
|
41449
42870
|
|
|
41450
42871
|
// src/drain-progress.ts
|
|
41451
42872
|
import {
|
|
41452
42873
|
chmodSync as chmodSync7,
|
|
41453
|
-
existsSync as
|
|
41454
|
-
readFileSync as
|
|
41455
|
-
readdirSync as
|
|
41456
|
-
rmSync as
|
|
42874
|
+
existsSync as existsSync17,
|
|
42875
|
+
readFileSync as readFileSync20,
|
|
42876
|
+
readdirSync as readdirSync5,
|
|
42877
|
+
rmSync as rmSync11,
|
|
41457
42878
|
rmdirSync
|
|
41458
42879
|
} from "fs";
|
|
41459
|
-
import { basename as basename3, dirname as dirname12, join as
|
|
42880
|
+
import { basename as basename3, dirname as dirname12, join as join25 } from "path";
|
|
41460
42881
|
|
|
41461
42882
|
// src/journal.ts
|
|
41462
|
-
var JOURNAL_DIR =
|
|
42883
|
+
var JOURNAL_DIR = join26(primConfigDirectory(), "moves");
|
|
41463
42884
|
var UNBOUND_BUCKET = "_unbound";
|
|
41464
42885
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
41465
42886
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
@@ -41471,7 +42892,7 @@ function envSlug(apiUrl) {
|
|
|
41471
42892
|
return slug;
|
|
41472
42893
|
}
|
|
41473
42894
|
function currentEnvDir() {
|
|
41474
|
-
return
|
|
42895
|
+
return join26(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
41475
42896
|
}
|
|
41476
42897
|
var DIR_MODE = 448;
|
|
41477
42898
|
var FILE_MODE2 = 384;
|
|
@@ -41479,23 +42900,24 @@ var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
|
|
|
41479
42900
|
var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
|
|
41480
42901
|
function appendMoveToPath(path, move) {
|
|
41481
42902
|
const dir = dirname13(path);
|
|
41482
|
-
if (!
|
|
41483
|
-
|
|
42903
|
+
if (!existsSync18(dir)) {
|
|
42904
|
+
mkdirSync9(dir, { recursive: true, mode: DIR_MODE });
|
|
41484
42905
|
}
|
|
41485
42906
|
appendFileSync(path, `${JSON.stringify(move)}
|
|
41486
42907
|
`, { mode: FILE_MODE2 });
|
|
41487
42908
|
}
|
|
41488
42909
|
function bucketDir(orgId) {
|
|
41489
42910
|
const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
|
|
41490
|
-
return
|
|
42911
|
+
return join26(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
|
|
41491
42912
|
}
|
|
41492
42913
|
function journalPath(orgId) {
|
|
41493
|
-
return
|
|
42914
|
+
return join26(bucketDir(orgId), JOURNAL_BASENAME);
|
|
41494
42915
|
}
|
|
41495
42916
|
function appendMove(move, orgId) {
|
|
41496
42917
|
const actor = machineCaptureActor();
|
|
41497
42918
|
const captured = actor ? { ...move, captureActor: actor } : move;
|
|
41498
|
-
|
|
42919
|
+
const bucket = actor ? identityPending(actor) ? machinePendingBucket(actor) : machineJournalBucket(actor) : orgId;
|
|
42920
|
+
appendMoveToPath(journalPath(bucket), captured);
|
|
41499
42921
|
return captured;
|
|
41500
42922
|
}
|
|
41501
42923
|
var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
|
|
@@ -41506,20 +42928,20 @@ async function deliverPostToolMove(move, orgId) {
|
|
|
41506
42928
|
const captured = appendMove(move, orgId);
|
|
41507
42929
|
const signal = AbortSignal.timeout(INGEST_TIMEOUT_MS);
|
|
41508
42930
|
const client = captured.captureActor ? await getPinnedClient({ signal }) : getClient();
|
|
41509
|
-
let
|
|
42931
|
+
let request3 = { batch: [captured] };
|
|
41510
42932
|
if (captured.captureActor) {
|
|
41511
42933
|
const binding = parseOrganizationBinding(
|
|
41512
42934
|
await client.get("/api/cli/auth/status", { signal, quietRefresh: true })
|
|
41513
42935
|
);
|
|
41514
42936
|
if (binding.state !== "current") throw new InvalidJournalEnvelopeError();
|
|
41515
|
-
|
|
42937
|
+
request3 = buildOrganizationBoundMoveRequest([captured], binding.binding);
|
|
41516
42938
|
}
|
|
41517
|
-
const response = await client.post("/api/cli/moves/ingest",
|
|
42939
|
+
const response = await client.post("/api/cli/moves/ingest", request3, { signal });
|
|
41518
42940
|
return requireDurableIngestAcknowledgement(response, 1, move.env.gitRoot ?? move.env.cwd);
|
|
41519
42941
|
}
|
|
41520
42942
|
|
|
41521
42943
|
// src/hooks/prim-hook-core.ts
|
|
41522
|
-
import { createHash as
|
|
42944
|
+
import { createHash as createHash13, randomUUID as randomUUID5 } from "crypto";
|
|
41523
42945
|
import { platform } from "os";
|
|
41524
42946
|
|
|
41525
42947
|
// src/protocol/move.ts
|
|
@@ -41593,9 +43015,9 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
|
|
|
41593
43015
|
const toolOutcome = toolOutcomeFor(parsed, agent);
|
|
41594
43016
|
let moveId;
|
|
41595
43017
|
if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && invocationId) {
|
|
41596
|
-
moveId = `posttool:v1:${
|
|
43018
|
+
moveId = `posttool:v1:${createHash13("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
|
|
41597
43019
|
} else if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && agent !== "cursor") {
|
|
41598
|
-
moveId = `posttool:fallback:v1:${
|
|
43020
|
+
moveId = `posttool:fallback:v1:${createHash13("sha256").update(
|
|
41599
43021
|
JSON.stringify([
|
|
41600
43022
|
agent,
|
|
41601
43023
|
sessionId,
|
|
@@ -41671,7 +43093,7 @@ function editingToolsFor(agent) {
|
|
|
41671
43093
|
var here = dirname14(fileURLToPath5(import.meta.url));
|
|
41672
43094
|
function resolveCliVersion() {
|
|
41673
43095
|
try {
|
|
41674
|
-
const pkg = JSON.parse(
|
|
43096
|
+
const pkg = JSON.parse(readFileSync22(join27(here, "..", "..", "package.json"), "utf-8"));
|
|
41675
43097
|
return pkg.version ?? "unknown";
|
|
41676
43098
|
} catch {
|
|
41677
43099
|
return "unknown";
|